【问题标题】:Postgres - converting rows to columns from two tablesPostgres - 将两个表中的行转换为列
【发布时间】:2017-12-18 08:09:47
【问题描述】:

数据是从两个具有一对可能关系的表中提取的。

查询:

 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】:

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

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

    【讨论】:

    • 我不会说换行符。基本上我在 item_type 0 下有一些记录(这成为名为 ear 的第 1 列。我需要在列值中显示金额)。同样,我有名为 add 的 item_type 1 的记录,我需要针对它显示值,依此类推)。所以我显示的结果集在 1 个主记录下有 6 个子记录。
    猜你喜欢
    • 2021-12-03
    • 1970-01-01
    • 2020-01-25
    • 2021-11-15
    • 1970-01-01
    • 2020-07-21
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多