按状态列出的PostgreSQL记录计数

按状态列出的PostgreSQL记录计数,sql,postgresql,Sql,Postgresql,在我的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 如何在Post

在我的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中做到这一点?

您可以尝试以下方法:

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;
或者,如果您愿意(它只使用两个聚合函数):

样本数据:

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
您可以尝试以下方法:

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;
或者,如果您愿意(它只使用两个聚合函数):

样本数据:

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
使用
count()

使用
count()