Postgres - 将行转换为两个表中的列

问题描述 投票:0回答:1

enter image description here

数据来自两个具有一个可能关系的表。

查询:

 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

我必须以这种方式显示数据

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

其他名称“我”与mh01相同如何在Postgres中执行此操作?应该是什么查询来实现此结果集。

sql postgresql pivot crosstab
1个回答
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;
© www.soinside.com 2019 - 2024. All rights reserved.