취미가 좋다

180. Consecutive Numbers 본문

SQL 문제풀이/Leetcode

180. Consecutive Numbers

benlee73 2021. 9. 29. 20:29

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

 

Consecutive Numbers - LeetCode

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

Solution

select distinct l.Num as ConsecutiveNums 
from Logs l left join Logs r 
on l.Num = r.Num and r.Id < l.Id and l.Id -r.Id <3 
group by l.Num,l.Id
having sum(l.Id-r.Id)=(0+1+2)
  • num이 같은 것을 모두 left join으로 붙인다.
    • 조건으로는 오른쪽에 붙는 쪽의 id가 더 작아야 한다.
    • 그리고 id의 격차가 3보다 작아야 한다.
  • l.id로 group by를 해도 통과는 한다. 그래서 왜 l.num도 group으로 묶어야 하는진 모르겠다.
  • sum(l-Id-r.Id) = (0+1+2)의 의미는, 연속된 것이 있을 때만 성립한다.
    • l.id - r.id = 0 일 때가 둘이 같을 때
    • l.id - r.id = 1 일 때가 바로 다음에 같은 num이 왔을 때
    • l.id - r.id = 2 일 때가 바로 다다음에 같은 num이 왔을 때

'SQL 문제풀이 > Leetcode' 카테고리의 다른 글

178. Rank Scores  (0) 2021.09.06
182. Duplicate Emails  (0) 2021.09.04
181. Employees Earning More Than Their Managers  (0) 2021.09.04
177. Nth Highest Salary  (0) 2021.08.13
176. Second Highest Salary  (0) 2021.08.13
Comments