2016-07-22 806 views
0

我想将具有相同ID的多行合并为一行。使用Postgresql将多行合并为一行

我的原始表看起来像这样:

ID | person_id | eur_amount 
1  3   200 
1  2   100 
2  3   80 
2  2   100 

输出应该是这样的:

ID | person_1 | eur_amount_1 | person_2 | eur_amount_2 | 
1  3   200   2   100 
2  3   80   2   100 

者的最大数量是相同的。我已经尝试用多个JOIN语句和交叉表()函数来解决它,如PostgreSQL Crosstab Query所述。

但我找不到解决方案 - 没有人知道达到所需输出的一种好方法吗?

在此先感谢!

+1

我的第一个问题是你为什么要这样做?但我会离题...是人事ID已经提前知道(IE查询只查找personID 2和3),并且是两个人的列的上限或你会有更多?这看起来像是你想让SQL去做报表GUI应该担心的事情。还应该问什么决定哪些价值进入person_1 vs person_2,是否只是行的顺序? – Twelfth

+0

'select_id,array_agg(person_id,eur_amount)order by person_id desc)作为perdata from my_raw_rable group by id;' – Abelisto

回答

0

您可以使用交叉表或条件聚合来做到这一点。但是您需要使用row_number()来识别行。例如:

select id, 
     max(case when seqnum = 1 then person_id end) as person_id_1, 
     max(case when seqnum = 1 then eur_amount end) as eur_amount_1, 
     max(case when seqnum = 2 then person_id end) as person_id_2, 
     max(case when seqnum = 2 then eur_amount end) as eur_amount_2 
from (select t.*, 
      row_number() over (partition by id order by id) as seqnum 
     from t 
    ) t 
group by id;