74

有谁知道如何重写以下 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的结果

4

2 回答 2

131

您可以在distinct里面使用关键字array_agg

SELECT ARRAY_TO_STRING(ARRAY_AGG(DISTINCT 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 这个例子

于 2014-10-14T14:52:17.660 回答
1

ARRAY_TO_STRING(ARRAY_AGG(当一个简单的STRING_AGG操作如下(这里的小提琴可用代码)时,无需到处走动:

--
-- Simplified
--

SELECT
  DISTINCT
  STRING_AGG
  (
    DISTINCT CONCAT(w.firstname, ' ', w.lastname), ', '
  ) AS "The workers"
FROM log_item li
INNER JOIN log l ON li.log_id = l.id 
INNER JOIN worker w ON l.worker_id = w.id
WHERE li.company_id = 1;

结果:

                The workers
Frantisek Smith, Peter Duff
于 2021-11-01T09:26:32.780 回答