2017-12-18 5 views
0

enter image description herePostgres - 2つのテーブルから列を列に変換する

データは1対5の関係を持つ2つのテーブルからフェッチされました。

問合せ:私は、これはPostgresの中で行うことができますどのように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

基本的な問題は、効果的に1つのケースでデータを集計し、値の間に改行を表示する必要があることです。あなたが使用する必要がどのような

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つの子レコードがあります。 –

関連する問題