我有一張桌子:
ID, color
---- ------
1 red
2 red
3 green
4 green
5 green
6 blue
7 blue
期望的查詢結果:
red 1,2
green 3,4,5
blue 6,7
如何在 Postgres SQL 中撰寫查詢?
uj5u.com熱心網友回復:
您正在尋找的是帶有可選 order by的array_agg 。在下文中,內部選擇為每種顏色構建有序 id 串列,然后外部查詢按顏色中的最低 id 值對整體結果進行排序。
with test( id, color) as
( values (1, 'red')
, (2, 'red')
, (3, 'green')
, (4, 'green')
, (5, 'green')
, (6, 'blue')
, (7, 'blue')
)
select color, arr as id_list
from (
select color, array_agg(id order by id) arr
from test
group by color
) sq
order by arr[1];
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/442341.html
標籤:PostgreSQL
下一篇:依靠SQL中帶有條件陳述句的列?
