본문 바로가기

SQL/LeetCode

[SQL] LeetCode: 180. Consecutive Numbers

180. Consecutive Numbers

 

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 컬럼을 이용해 푸는 풀이도 있었음