2012-02-22 53 views
21

我有這個疑問得到的PlayerSession s的reconnect = TRUE數量,由Player.country分組:計數行與聚集查詢特定條件

SELECT 
    country, 
    COUNT(*) AS with_reconnect 
FROM PlayerSession S LEFT JOIN Player P ON (P.id = S.player_id) 
WHERE reconnect = TRUE 
GROUP BY country 

我想修改它顯示不只是重新連接會議計數,但也是總數,如:

SELECT 
    country, 
    COUNT(*) AS total, 
    (COUNT WHERE reconnect = TRUE) AS with_reconnect 
FROM PlayerSession S LEFT JOIN Player P ON (P.id = S.player_id) 
GROUP BY country 

這是可能的,如果是這樣,什麼是正確的語法?

+0

見http://stackoverflow.com/questions/4414539/easiest-way-to-get- a-total-count-and-a-subset-of-subset – kaj 2012-02-22 12:36:35

回答

49
SELECT Country, 
     COUNT(*) AS Total, 
     COUNT(CASE WHEN Reconnect = true THEN 1 END) AS With_Reconnect 
FROM PlayerSession S 
     LEFT JOIN Player P 
      ON P.id = S.player_id 
GROUP BY country 
0
SELECT 
    country, 
    COUNT(*) AS total, 
    sum(case when reconnect = TRUE then 1 else 0 end) AS with_reconnect 
FROM PlayerSession S LEFT JOIN Player P ON (P.id = S.player_id) 
GROUP BY country 
16

以下就足夠了

SELECT 
    p.country, 
    COUNT(*) AS total, 
    SUM(IF(s.reconnect=TRUE,1,0)) AS with_reconnect 
FROM PlayerSession s 

INNER JOIN Player p 
ON p.id = s.player_id 

GROUP BY p.country 

我只是改寫了查詢。每個PlayerSession都會有一個Player行,所以將其更改爲INNER JOIN。也沒必要的CONCAT,因爲總是會在此查詢PlayerSession行(除非沒有會話)

+0

嗯,看起來括號不匹配。 – 2012-02-22 12:38:12

+0

對不起,括號內失明,修正:) – 2012-02-22 12:40:14

+3

在一次快速測試中,我發現此處顯示的SUM(IF())方法比接受的答案中顯示的COUNT(CASE)方法快。 – arlomedia 2012-03-27 23:55:24

1
SELECT 
    country, 
    COUNT(CASE WHEN reconnect = TRUE THEN S.player_id ELSE NULL END) AS with_reconnect, 
    COUNY(*) 
FROM PlayerSession S LEFT JOIN Player P ON (P.id = S.player_id) 
GROUP BY country 
+0

'ELSE NULL'是多餘的,如果你沒有指定'ELSE'的結果是'NULL',但這是相當微不足道的,我很喜歡使用'COUNT'而不是'SUM(CASE WHEN ... THEN 1 ELSE 0 END)'當期望的結果是一個計數而不是一個總和時,所以你得到了我的投票!還請將COUNY更改爲COUNT ... – GarethD 2012-02-22 12:43:52

+0

@GarethD - 我知道這是多餘的,但它使這種方式更加清晰 – Lamak 2012-02-22 13:08:57