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

[LeetCode] - 180. Consecutive Numbers

by 소복소복뚜벅뚜벅 2024. 3. 27.

문제 

Find all numbers that appear at least three times consecutively.

Return the result table in any order.

The result format is in the following example.

 

 

문제풀이 

SELECT DISTINCT num AS ConsecutiveNums
FROM (
    SELECT num
        , LEAD(num,1) OVER (ORDER BY id) AS num_1_after 
        , LEAD(num,2) OVER (ORDER BY id) AS num_2_after 
    FROM Logs 
) nums 
WHERE num = num_1_after 
AND num = num_2_after

 

1. LEAD() 윈도우 함수를 이용해서 다음에 오는 숫자를 끌어온다. (최소 3번이니깐 2개를 가져온다.) 

2. 그 다음 현재 숫자와 그 다음에 오는 숫자의 값이 동일한지 확인하고, 현재 숫자와 두번째로 오는 숫자의 값이 동일한지 확인한다 => 연속적으로 최소 3번까지 같은 숫자임을 확인하는 조건 

 

오답 

1. Window 함수를 쓸 생각을 하지 못함. 

2. num_1_after 과 num_2_after 가 동일한지 먼저 조건을 설정해버림