繁体   English   中英

Postgres-将行从两个表转换为列

[英]Postgres - converting rows to columns from two tables

在此处输入图片说明

数据已从两个具有一一可能关系的表中获取。

查询:

 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的其他名称“ Me”相同。如何在Postgres中执行此操作? 要实现此结果集的查询应该是什么。

您的基本问题是,您需要在一种情况下有效地汇总数据,然后在值之间使用换行符进行显示,对吗?

您需要使用的是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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM