본문 바로가기
프로그래밍/SQL, Hive, SAS 관련 정보

[SQL문제풀이] - 명시적 Group이 없을 때 Grouping (2)

by TrillionNT 2025. 3. 14.

2025.02.24 - [프로그래밍/SQL, Hive, SAS 관련 정보] - [SQL] Table of Contents


https://leetcode.com/problems/human-traffic-of-stadium/description/

 

이 문제의 어려운 포인트는 그룹화를 하긴 해야하는데.. 동일한 값이 있는 것으로 그룹화를 하는 것이 아니라 "연속"조건으로 그룹화를 시키는 것입니다. 이전에 유사한 문제가 있었던 것 같습니다. 

2025.01.19 - [프로그래밍/SQL, Hive, SAS 관련 정보] - [SQL 문제풀이] - 명시적 Group이 없을 때 Grouping (1)

 

WITH FilteredStadium AS (
    SELECT 
        id, TO_CHAR(visit_date, 'yyyy-mm-dd') visit_date, people
        , ROW_NUMBER() OVER (ORDER BY id) AS row_num
        , id - ROW_NUMBER() OVER (ORDER BY id) AS date_group
    FROM Stadium
    WHERE people >= 100
)
SELECT
    id, visit_date, people
FROM FilteredStadium
WHERE date_group IN (
    SELECT date_group
    FROM FilteredStadium
    GROUP BY date_group
    HAVING COUNT(*) >= 3
)
ORDER BY visit_date;

 

with절을 쓰지않고 서브쿼리를 활용한 MySQL코드는 아래와 같습니다. 

select t.id, t.visit_date, t.people
from 
   (select s.id, s.visit_date, s.people, count(s.id) over (partition by s.id-s.rn) cnt 
    from 
        (select f.*, row_number() over (order by f.id) rn 
         from stadium f where f.people>=100) s) t where cnt>=3
order by t.visit_date asc;

'프로그래밍 > SQL, Hive, SAS 관련 정보' 카테고리의 다른 글

[SQL기초] 형 변환  (0) 2025.03.22
[SQL 기초] Self 조인  (0) 2025.03.17
[SQL 기초] To_date (Oracle)  (0) 2025.03.13
[SQL문제풀이] Join Key의 처리  (0) 2025.03.09
[SQL 기초] 날짜형식 연/월/일  (0) 2025.02.26