2017-12-18 155 views
0

enter image description herePostgres的 - 从两个表

的数据已经从具有一个至5月关系两个表取出转换行列。

查询:

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 

我有我如何能做到这一点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 

同为其他名称为 “我”?实现这个结果集的查询应该是什么。

回答

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; 
+0

我不会说换行符。基本上我有一些记录下的item_type 0(这成为列1命名为耳朵,我需要显示的数额与列值相比)。同样,我有记录item_type 1命名为添加我需要显示值等等)。所以我显示的结果集在1个主记录下有6个子记录。 –