2016-07-22 43 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;