【发布时间】:2014-12-09 10:04:52
【问题描述】:
有没有人知道如何重写以下 SQL 查询以生成只包含一次出现的名称的结果? (按用户分组的结果)。
查询
SELECT array_to_string(array_agg(CONCAT(u.firstname, ' ', u.lastname)), ', ')
FROM log_has_item logitem
INNER JOIN log log ON log.id = logitem.log_id
INNER JOIN worker u ON log.worker_id = u.id
WHERE logitem.company_id = 1
sqlfiddle.com 上提供可执行查询。 单击运行 SQL 按钮,您将得到结果,其中包含 Frantisek Smith 两次
【问题讨论】:
-
array_agg(distinct concat(...))) -
在 postgre 9.0+ 中有
string_agg(text,text)函数。写string_agg(CONCAT(...),', ')可能更容易 -
@a_horse_with_no_name distinct 工作正常,但会打乱顺序。有什么办法保存吗?
-
@Rodrigo:在
string_agg()内使用order by -
@a_horse_with_no_name 我尝试了 string_agg(distinct nome order by l.id,', ') 和 string_agg(distinct nome order by nome,', '),但两者都给出“函数 string_agg(字符变化)不存在”。我会用完整的sql问一个问题给你看。
标签: sql postgresql select array-agg