문제
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번째 다음) 의 경우만 생각했다. 다른 경우의 수를 생각하지 못했다.
'취준 > 코팅 테스트' 카테고리의 다른 글
[LeetCode] 1484. Group Sold Products By The Date (0) | 2024.04.06 |
---|---|
[LeetCode] 626. Exchange Seats (0) | 2024.04.05 |
[LeetCode] - 1661. Average Time Of Process per Machine (0) | 2024.04.04 |
[LeetCode] - 1321. Restaurant Growth (0) | 2024.04.03 |
[LeetCode] 1978. Employees Whose Manager Left the Company (0) | 2024.04.01 |