select 所有行值作为列表

select all row values as a list

我有一个 table tasks 看起来像这样:

userId          caption    status       id
1               Paul       done         1
2               Ali        notDone      18
3               Kevin      notDone      12
3               Elisa      notDone      13

我将它与另一个 table users 结合起来,以查找 tasks 其中 status = notDone 的数量。我这样做:

    SELECT u.id, 
       t.number_of_tasks,
    FROM users u
    INNER JOIN (
      SELECT userId, COUNT(*) number_of_tasks
      FROM tasks 
      WHERE status = "notDone"
      GROUP BY userId
      ) t ON u.id = t.userId
    """

现在,我想创建另一个列 captions,以某种方式包含 count 中包含的所有 captions 的列表,并满足连接 + where 条件。

例如,我希望这是其中一行。我怎样才能做到这一点?

userId      number_of_tasks     captions
3           2                   ["Kevin", "Elisa"]

您可以在子查询中使用 json_group_array() 聚合函数为每个用户创建字幕列表:

SELECT u.id, t.number_of_tasks, t.captions
FROM users u 
INNER JOIN (
  SELECT userId, 
         COUNT(*) number_of_tasks,
         json_group_array(caption) captions
  FROM tasks 
  WHERE status = 'notDone'
  GROUP BY userId
) t ON u.id = t.userId;