【问题标题】:SQL subquery rows as GROUP BY columnsSQL 子查询行作为 GROUP BY 列
【发布时间】:2020-07-02 01:04:46
【问题描述】:

我想在每个task_type 的响应中都有列,计数按date_trunc('day')user_id 分组。因此,一旦整个查询运行,它将返回 task_type_1 列,字段值将是给定用户在给定日期具有该类型的任务数。

到目前为止,我有这个运行但不确定如何将 task_type 分组添加到此查询:

SELECT users.id AS user_id,
  date_trunc('day', workforce_assigned_tasks.created_at) AS day,
  SUM(workforce_assigned_tasks.duration) AS duration,
  SUM(workforce_assigned_tasks.earnings_cents) AS earnings_cents,
  SUM(workforce_assigned_tasks.subtask_count) AS subtask_count,
  WHAT GOES HERE?
FROM users
JOIN workforce_assigned_tasks ON workforce_assigned_tasks.user_id = users.id
JOIN workforce_tasks ON workforce_assigned_tasks.workforce_task_id = workforce_tasks.id
GROUP BY date_trunc('day', workforce_assigned_tasks.created_at), users.id;

【问题讨论】:

  • 提供样本数据和期望的结果。

标签: sql postgresql grouping aggregate-functions


【解决方案1】:

您可以使用条件聚合,在 Postgres 中使用 FILTER 子句:

SELECT u.id AS user_id, date_trunc('day', wat.created_at) AS day,
       SUM(wat.duration) AS duration,
       SUM(wat.earnings_cents) AS earnings_cents,
       SUM(wat.subtask_count) AS subtask_count,
       COUNT(*) FILTER (WHERE wt.task_type_1 = 1)
FROM users u JOIN
     workforce_assigned_tasks wat
     ON wat.user_id = u.id JOIN
     workforce_tasks wt
     ON wat.workforce_task_id = wt.id
GROUP BY date_trunc('day', wat.created_at), u.id;

我猜task_typeworkforce_tasks 中。

请注意,表别名的使用使查询更易于编写和阅读。

【讨论】:

  • 在这种情况下,我将不得不重复这一行,次数与数据库中的类型一样多:WHERE wt.task_type_1 = 1?有没有办法以某种方式进行循环?
  • 否,但您可以复制并越过该行,更改每一行的参数。
  • 还有一个问题。它可以以某种方式返回为像col名称tasks_counts和json值{ "type_1": 10, "type_2": 20 }这样的json字段吗?我花了一些时间,但想不通。
  • @SeanMagyar 。 . .您可以使用 Postgres 中的 JSON 构造函数和函数构造 JSON 字段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
相关资源
最近更新 更多