【问题标题】:In PostgreSQL, how to query for a computed results by the grouping of a field?在 PostgreSQL 中,如何通过字段的分组来查询计算结果?
【发布时间】:2020-07-12 14:56:23
【问题描述】:

在我的 PostgreSQL 数据库中,我有一个邀请表,如下所示:

邀请表:

id, created_at, source, completed_at

字段详情

id: integer
created_at: timestamp
source: varchar
completed_at: timestamp

我想查询 Invitations 表并按唯一来源分组。然后每个来源,包括记录总数和已完成记录总数。在 complated_at 不是 NULL 的地方完成。

期望的结果:

columns: source, total, total_completed

source_a | 100 | 50
source_b | 200 | 33
source_c | 301 | 3

建议?

【问题讨论】:

  • 提示:GROUP BY.

标签: sql database postgresql group-by count


【解决方案1】:

你可以像这样进行聚合:

select source,  count(*) total, count(completed_at) total_completed
from invitations
group by source

count(*) 统计组中的所有记录,而count(completed_at) 只统计completed_at 不是null 的记录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    相关资源
    最近更新 更多