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

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

by 물박사의 저장공간 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 temp AS
    (select id, visit_date, id - row_number() over(order by visit_date) gr, people
    from Stadium
    where people>100)
select id, visit_date, people
from temp
where gr in (select gr from temp group by gr having count(*)>=3)
order by visit_date asc;

 

참고로 이 코드는

https://trillionver2.tistory.com/entry/SQL-%EA%B8%B0%EC%B4%88-CTE%EC%99%80-Sub-query%EC%9D%98-%EC%B0%A8%EC%9D%B4

 

[SQL 기초] CTE와 Sub-query의 차이

2025.02.24 - [프로그래밍/SQL, Hive, SAS 관련 정보] - [SQL] Table of ContentsCTE는 쿼리 전체에서 재사용이 가능하며, 서브쿼리 내부에서도 참조할 수 있습니다.select user_id from (select user_id, count(movie_id) cnt from

trillionver2.tistory.com

포스팅과도 연관이 있다고 볼 수 있겠습니다.

 

 

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