2015-02-07 56 views
1

如何在一個查詢中統計表participants中的記錄總數,用戶唯一數和狀態爲2的記錄數?ONE SQL查詢來計算不同條件下的記錄

我知道如何使用3個單獨的查詢來實現: SELECT COUNT()參與者 SELECT COUNT()參與者GROUP BY用戶 SELECT COUNT(*)FROM參加WHERE狀態= 2

但是這看起來效率不高?

participants

id   user   status 
10  [email protected]  1  
11  [email protected]  1  
12  [email protected]  1  
13 [email protected]  1  
14 [email protected]  2  
15 [email protected] 1  
16 [email protected] 1  
17 [email protected] 2 
18  [email protected]  2  
19  [email protected]  1 
29  [email protected]  0 

回答

0

只需使用條件彙總:

select count(*) as numrecords, count(distinct user) as numusers, 
     sum(status = 2) as numstatus_2 
from participants p; 
0

既然你只想要一個結果(按規定),你不需要group by條款可言的,所有的這些要求可以創建作爲count函數參數:

SELECT COUNT(*) AS total_records, 
     COUNT(DISTINCT user) AS distinct_users_count, 
     COUNT(CASE status WHEN 2 ELSE NULL END) AS status_2_count 
FROM participants