J'ai cette requête pour obtenir le nombre de PlayerSession
s avec reconnect = TRUE
, groupés par 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
Je voudrais le modifier pour afficher non seulement le nombre de sessions reconnectées, mais également le nombre total, quelque chose comme:
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
Est-ce possible, et si oui, quelle est la syntaxe appropriée?
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
Ce qui suit suffira
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
Je viens de réécrire la requête. Vous aurez toujours une ligne Player pour chaque PlayerSession. Vous devez donc la changer pour une INNER JOIN. De plus, CONCAT n'était pas nécessaire car il y aura toujours des lignes PlayerSession dans cette requête (sauf s'il n'y a pas de session).
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
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