반응형
    
    
    
  집계 쿼리에서 특정 조건을 가진 행 수 계산
나는 이 쿼리를 가지고 있습니다.PlayerSession와의.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
이것이 가능하며, 가능하다면 적절한 구문은 무엇입니까?
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
다음으로 충분합니다.
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
방금 질문을 다시 작성했습니다.플레이어 세션마다 플레이어 행이 항상 있으므로 내부 조인으로 변경합니다.또한 이 쿼리에는 항상 플레이어 세션 행이 있기 때문에 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
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
언급URL : https://stackoverflow.com/questions/9394758/count-rows-with-a-specific-condition-in-aggregate-query
반응형
    
    
    
  'programing' 카테고리의 다른 글
| Spark DataFrame에 빈 열 추가 (0) | 2023.10.23 | 
|---|---|
| data.frame에서 data.frame으로 단일 열을 추출하려면 어떻게 해야 합니까? (0) | 2023.10.23 | 
| Amazon LightSail 403 루트 계정 오류 (0) | 2023.10.23 | 
| SQL(ORACLE)의 악센트를 무시하는 문자열 비교 (0) | 2023.10.23 | 
| 깃 저장소를 다른 디렉터리로 이동하고 해당 디렉터리를 깃 저장소로 만드는 방법? (0) | 2023.10.18 |