PostgreSQL 按状态统计的记录数
Posted
技术标签:
【中文标题】PostgreSQL 按状态统计的记录数【英文标题】:PostgreSQL count of records by status 【发布时间】:2018-02-06 18:03:36 【问题描述】:在我的 PostgreSQL 数据库中,我有 users
表,其中包含以下列:
id - integer
email - string
blocked - boolean
现在我想要 sql 查询返回以下结果:
total: blocked: unblocked
total count of users count of blocked users count of users that are not blocked
如何在 PostgreSQL 中做到这一点?
【问题讨论】:
【参考方案1】:你可以试试这个:
SELECT COUNT(ID) AS USER_RC
, SUM(CASE WHEN BLOCKED=TRUE THEN 1 ELSE 0 END) AS BLOCKED_RC
, SUM(CASE WHEN BLOCKED=TRUE THEN 0 ELSE 1 END) AS UNBLOCKED_RC
FROM TX1;
或者如果您愿意(它只使用两个聚合函数):
SELECT A.*, USER_RC-BLOCKED_RC AS UNBLOCKED_RC
FROM (SELECT COUNT(ID) AS USER_RC, SUM(CASE WHEN BLOCKED=TRUE THEN 1 ELSE 0 END) AS BLOCKED_RC
FROM TX1) A
;
样本数据:
INSERT INTO TX1 VALUES (1,'aaa',FALSE);
INSERT INTO TX1 VALUES (2,'bbb',TRUE);
INSERT INTO TX1 VALUES (3,'ccc',TRUE);
INSERT INTO TX1 VALUES (4,'ddd',TRUE);
INSERT INTO TX1 VALUES (5,'eee',FALSE);
输出:
user_rc blocked_rc unblocked_rc
5 3 2
【讨论】:
【参考方案2】:将count()
与filter: 一起使用
select
count(*) as total,
count(*) filter (where blocked) as blocked,
count(*) filter (where not blocked) as unblocked
from users
【讨论】:
以上是关于PostgreSQL 按状态统计的记录数的主要内容,如果未能解决你的问题,请参考以下文章