Count rows with a specific condition in aggregate query

Bart van Heukelom picture Bart van Heukelom · Feb 22, 2012 · Viewed 42.4k times · Source

I have this query to get the number of PlayerSessions with reconnect = TRUE, grouped by 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

I'd like to modify it to show not just the reconnected session count, but also the total count, something like:

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

Is this possible, and if so, what is the proper syntax?

Answer

GarethD picture GarethD · Feb 22, 2012
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