2017-06-22 207 views
0

比方說,我有以下數據:彙總數據

gp_id | p_id 
------|------- 
1  | 123 
2  | 432 
2  | 222 

業務邏輯的目的,我要變換成這樣:

gp_id | p_ids 
------|---------- 
1  | {123} 
2  | {432,222} 

我試圖做一些事情像這樣(實際上,我知道這是錯誤的方法,但仍然):

select gp_id, array(
    select p_id from cte 
    ) as p_ids 
from cte 

而且,可以預見的是,嗯,它返回以下內容:

gp_id | p_ids 
------|-------------- 
1  | {123,432,222} 
2  | {123,432,222} 
2  | {123,432,222} 

任何人都可以請幫助我嗎?
是的,事實上,我在一系列通用表表達式中使用它。

回答

1

試試下面的查詢:

select c1.gp_id, array(
    select p_id from cte c2 where c2.gp_id = c1.gp_id 
    ) as p_ids 
from cte c1 group by c1.gp_id; 

OR

select gp_id, group_concat(p_id) p_ids 
from cte group by gp_id; 
+0

謝謝你,我在你的幫助下學到了很多東西!我對sql有一個很小的練習,而且你展示了一個擴展我的理解的好方法。 –

+0

當然。歡迎。您也可以選擇使用group_concat。 –

+0

不好意思再次打擾你,但是請你給我一點關於如何將數組放入不同值的提示? –

3

我認爲你可以使用array_agg

select 
    gp_id, array_agg(p_id) as p_ids 
from cte 
group by gp_id 
+0

這是絕對偉大和乾淨的解決方案,非常感謝你! –