PostgreSQL按状态计数记录

时间:2017-08-29 10:13:01

标签: 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

我怎样才能在PostgreSQL中做到这一点?

2 个答案:

答案 0 :(得分: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;

或者如果您愿意(它只使用两个聚合函数):

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

答案 1 :(得分:2)

timestamp max.price max.volume sum.price sum.volume 1 2017-08-29 08:00:00 99.1 10 197.3 15 2 2017-08-29 08:00:00 98.2 5 98.2 5 3 2017-08-29 16:00:00 97.0 5 193.5 8 4 2017-08-29 16:00:01 96.5 5 96.5 5 min.price min.volume 1 98.2 5 2 98.2 5 3 96.5 3 4 96.5 5 filter:

一起使用
count()