LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
<풀이>
-- 1. 출력: 3번 이상 연속으로 나오는 숫자
-- 2. 필터: 3번 이상 연속
-- 3. 정렬: X
SELECT DISTINCT num AS ConsecutiveNums
FROM(
SELECT *
,LAG(num,1) OVER (ORDER BY id) AS lag1
,LAG(num,2) OVER (ORDER BY id) AS lag2
FROM logs
)sub
WHERE num = lag1 AND lag1 = lag2
수열 중에서 3번 이상 연속으로 나오는 수를 찾는 문제
윈도우 함수 중 LAG( ) 함수를 이용해서 풀었다.
* LAG( ) : 데이터 앞에 있는 값을 가져옴
LAG 함수로 앞 2개의 값을 불러와 3연속 수가 같은지 확인하는 방법으로 풀이함.
** WHERE 절에서 id 컬럼을 이용해 푸는 풀이도 있었음
'SQL > LeetCode' 카테고리의 다른 글
| [SQL] LeetCode: 1164. Product Price at a Given Date (0) | 2024.03.09 |
|---|---|
| [SQL] LeetCode: 610. Triangle Judgement (0) | 2024.02.08 |
| [SQL] LeetCode : 184. Department Highest Salary (0) | 2024.01.31 |
| [SQL] LeetCode: 1789. Primary Department for Each Employee (1) | 2024.01.26 |
| [SQL] LeetCode: 1731. The Number of Employees Which Report to Each Employee (0) | 2024.01.17 |