【问题标题】:Concat results with PostgreSQL使用 PostgreSQL 连接结果
【发布时间】:2016-03-30 18:31:59
【问题描述】:

我正在使用 PostgreSQL。我有一张带有列的表:id、city、country。 每个国家/地区都有几个城市。

例如:

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)

我该怎么做?

【问题讨论】:

标签: sql node.js postgresql select concatenation


【解决方案1】:

根据您希望在结果集中获得什么 - 您可以使用 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;

【讨论】:

    猜你喜欢
    • 2013-04-12
    • 1970-01-01
    • 2023-03-30
    • 2018-07-08
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 2010-12-23
    • 2011-10-10
    相关资源
    最近更新 更多