2017-08-29 55 views
1

記錄在我的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

使用count()filter:

select 
    count(*) as total, 
    count(*) filter (where blocked) as blocked, 
    count(*) filter (where not blocked) as unblocked 
from users 
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