본문 바로가기
취준/코팅 테스트

[LeetCode] - 601. Human Traffic Of Stadium

by 소복소복뚜벅뚜벅 2024. 4. 5.

문제 

Write a solution to display the records with three or more rows with consecutive id's, and the number of people is greater than or equal to 100 for each.

Return the result table ordered by visit_date in ascending order.

 

 

문제풀이 

WITH df AS(
    SELECT *
        ,  LEAD(people,1) OVER (ORDER BY id) AS nxt_1 
        ,  LEAD(people,2) OVER (ORDER BY id) AS nxt_2 
        ,  LAG (people,1) OVER (ORDER BY id) AS pre_1 
        ,  LAG (people,2) OVER (ORDER BY id) AS pre_2 
    FROM Stadium 
) 

SELECT id
    ,  visit_date 
    ,  people
FROM df 
WHERE (people >= 100 AND nxt_1 >= 100 AND nxt_2>=100) OR 
      (people >= 100 AND pre_1 >= 100 AND pre_2>=100) OR 
      (people >= 100 AND pre_1 >= 100 AND nxt_1>=100)

 

1. 3개의 연속적인 id를 찾아야 하기 때문에 윈도우 함수의 LEAD() , LAG()을 사용한다. 그래서 이전행, 2번째 이전행, 다음행, 2번째 다음행의 people 값을 도출한다. 

 

2. 각각 연속적은 id의 people 값들이 100이 넘는 조건을 WHERE 절로 이용한다. 단, (현재, 이전, 1번째 이전) ,(현재, 다음, 2번째 다음) , (이전, 현재, 다음) 이런 경우에 3개의 연속적인 값들을 파악할 수 있다. 

 

오답이유

(현재, 다음, 2번째 다음) 의 경우만 생각했다. 다른 경우의 수를 생각하지 못했다.