2012-02-22 34 views
21

ho questa query per ottenere il numero di PlayerSession s con reconnect = TRUE, raggruppati per Player.country:righe contare con una condizione specifica nella query aggregata

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 

I desideri modificare per mostrare non solo la ricollegato conteggio della sessione, ma anche il conteggio totale, qualcosa come:

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 

questo è possibile, e se sì, qual è la sintassi corretta?

+0

Vedi http://stackoverflow.com/questions/4414539/easiest-way-to-get- a-total-count-and-a-count-of-a-subset per vari approcci – kaj

risposta

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

Di seguito sarà sufficiente

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 

Ho appena riscritto la query. Avrai sempre una riga Player per ogni PlayerSession, quindi l'hai cambiata in INNER JOIN. Anche il CONCAT non era necessario, come ci saranno sempre le righe PlayerSession in questa query (a meno che non ci sono sessioni)

+0

Hmm, sembra che le parentesi non coincidano. –

+0

Ci scusiamo, cecità staffa, risolto :) –

+3

In un test rapido, ho trovato che il metodo SUM (IF()) mostrato qui era più veloce del metodo COUNT (CASE) mostrato nella risposta accettata. – arlomedia

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' è ridondante, se non si specifica un' ELSE' il risultato è 'NULL', tuttavia questo è abbastanza banale e io sono un fan dell'uso di' COUNT' piuttosto che di 'SUM (CASE WHEN ... THEN 1 ELSE 0 FINE) 'quando il risultato desiderato è un conteggio e non una somma, quindi hai ottenuto il mio voto! Cambia anche COUNY in COUNT ... – GarethD

+0

@GarethD - So che è ridondante, ma lo rende più chiaro in questo modo – Lamak

Problemi correlati