2017-12-18 1 views
0

enter image description herePostgres - 두 테이블의 행을 열로 변환

데이터가 1 ​​대 5의 관계를 갖는 두 테이블에서 가져 왔습니다.

검색어 : 내가이 포스트 그레스에서 할 수있는 방법 mh01 으로이 방법으로 "나"다른 이름

code name ear value  add value  ded value 
001  Nav  BASIC 1000.00 HR 600.00 PF 50.00 
       FUEL 200.00  
       Mobile 300.00 

같은 데이터를 표시해야

select temp1.code, temp1.name, temp_dt.item_type, 
    (select item_name from pr_payroll_item where xid = temp_dt.payroll_item_xid 
    ), 
    temp_dt.amount from pr_template temp1, pr_template_detail temp_dt 
    where temp1.xid = temp_dt.parent_xid; 
Item Type 
0 ear 
1 add 
2 ded 

? 이 결과 집합을 얻기위한 쿼리는 무엇이되어야합니다.

답변

0

기본 문제는 데이터를 효과적으로 하나의 사례에 집계하고 값 사이에 줄 바꿈을 사용하여 표시해야하는 것입니다. 사용할 필요가있는 무엇

array_to_stringarray_agg하고 이론적으로는 기본적으로 order by 절을 필요로하지만, 그렇게 행하기 위해 사용합니다 :

select temp1.code, temp1.name, temp_dt.item_type, 
(select item_name from pr_payroll_item where xid = temp_dt.payroll_item_xid 
), 
temp_dt.amount from pr_template temp1, pr_template_detail temp_dt 
where temp1.xid = temp_dt.parent_xid; 

이 (수 있도록 편집 등 더 읽기 조인)이되다를 :

select temp1.code, temp1.name, 
     array_to_string(array_agg(temp_dt.item_type::text), E'\n') as eid, 
     array_to_string(array_agg(i.item_name), E'\n') as ear, 
     array_to_string(array_agg(temp_dt.amount::text)E'\n') as value 
    from pr_template_detail temp_dt 
    join pr_template temp1 on temp1.xid = temp_dt.parent_xid 
    join pr_payroll_item I on xid = temp_dt.payroll_item_xid 
group by temp1.code, temp1.name; 
+0

줄 바꿈을 말하지 않습니다. 기본적으로 item_type 0 아래에 몇 가지 레코드가 있습니다 (이 값은 귀로 명명 된 열 1이됩니다. 열 값에서 해당 값을 표시해야합니다). 마찬가지로 나는 item_type 1에 대한 레코드를 가지고 있는데, add라는 이름은 그 값을 보여줄 필요가있다. 따라서 표시된 결과 세트에는 1 개의 마스터 레코드 아래에 6 개의 하위 레코드가 있습니다. –