web-dev-qa-db-ja.com

集計クエリで特定の条件を持つ行をカウントします

私はreconnect = TRUEでグループ化されたPlayer.countryPlayerSessionsの数を取得するためにこのクエリを持っています:

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

これは可能ですか?可能な場合、適切な構文は何ですか?

27
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
60
GarethD

以下で十分です

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に変更しました。また、このクエリには常にPlayerSession行があるため、CONCATは必要ありませんでした(セッションがない場合を除く)

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
1
Lamak
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
0
Vikram