PostgreSQL按状态统计记录数

3

我在我的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中实现这个功能?
2个回答

3
您可以尝试这个:
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

3

使用 count() 结合 filter 来实现:

select
    count(*) as total,
    count(*) filter (where blocked) as blocked,
    count(*) filter (where not blocked) as unblocked
from users

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接