2016-03-30 50 views
-1

我正在使用PostgreSQL。我有一張桌子,裏面有列:id,城市,國家。 我有幾個城市爲每個國家。使用PostgreSQL的Concat結果

例如:

ID  Country  City 
1  Brazil  Rio de Janeiro 
2  Argentina Buenos Aires 
3  Argentina Bariloche 

而且我希望有一個SELECT返回類似

Country  Cities 
Brazil  (Rio de Janeiro) 
Argentina (Buenos Aires, Bariloche) 

我該怎麼辦呢?

+1

你到目前爲止嘗試過什麼? http://www.postgresql.org/docs/9.4/static/functions-aggregate.html –

+1

可能的重複http://stackoverflow.com/questions/29557563/whats-the-equivalent-for-listagg-in-postgres – leqid

+0

改進了格式 – showdev

回答

0

根據你想要得到的結果集 - 你可以使用array_agg()string_agg()函數。

WITH t(id,country,city) AS (VALUES 
    (1,'Brazil','Rio de Janeiro'), 
    (2,'Argentina','Buenos Aires'), 
    (3,'Argentina','Bariloche') 
) 
SELECT country,'(' || string_agg(city,',') || ')' FROM t 
GROUP BY country;