Postgres - converting rows to columns from two tables

时间:2017-12-18 08:09:47

标签: sql postgresql pivot crosstab

enter image description here

The data has been fetched from two tables which have one to may relationship.

Query:

{ "personalizations": 'to' and 'subject' here
  "from": ...
  "content": ... }
 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;

I have to display data in this way

Item Type 
0 ear
1 add
2 ded

same for other name "Me" with mh01 How can I do this in Postgres? What should be the query to achieve this result set.

1 个答案:

答案 0 :(得分: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;