mysql 문제풀이/easy

180. Consecutive Numbers

gooreumsea 2024. 1. 15. 23:21

https://leetcode.com/problems/consecutive-numbers/description/

기존에 테이블 조인 방식으로 풀었던 문제이지만, LEAD() 를 활용해서도 풀어볼 수 있었다.
큰 차이는 없지만, 윈도우함수를 활용하는 방법이 조금 더 직관적으로 이해하기 좋았음.

 

 

id NUM next afternext
1 1 1 1
2 1 1 2
3 1 2 1
4 2 1 2
5 1 2 2
6 2 2 null
7 2 null null

 

 

1) 윈도우 함수 풀이: LEAD

SELECT DISTINCT l.NUM AS ConsecutiveNums
FROM(
     SELECT NUM
          , LEAD(NUM,1) OVER (ORDER BY id) AS next
          , LEAD(NUM,2) OVER (ORDER BY id ) AS afternext
     FROM logs
 ) l
WHERE l.Num=next AND l.next=l.afternext




2) JOIN : 기존에 풀었던 방식

SELECT DISTINCT l.num AS ConsecutiveNums
FROM logs AS l
           INNER JOIN logs AS l_next ON l.id + 1 = l_next.id
           INNER JOIN logs AS l_next2 ON l.id + 2 =  l_next2.id

WHERE l.num = l_next.num AND l_next.num = l_next2.num