inblog logo
|
stupefyee
    SQL문제풀기

    [SQL 문제 풀이] Consecutive Numbers (연속된 숫자)

    Stupefyee's avatar
    Stupefyee
    Jun 03, 2025
    [SQL 문제 풀이] Consecutive Numbers (연속된 숫자)
    Contents
    내가 작성한 쿼리
    Consecutive Numbers - LeetCode
    Can you solve this real interview question? Consecutive Numbers - Table: Logs +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | num | varchar | +-------------+---------+ In SQL, id is the primary key for this table. id is an autoincrement column starting from 1.   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.   Example 1: Input: Logs table: +----+-----+ | id | num | +----+-----+ | 1 | 1 | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 1 | | 6 | 2 | | 7 | 2 | +----+-----+ Output: +-----------------+ | ConsecutiveNums | +-----------------+ | 1 | +-----------------+ Explanation: 1 is the only number that appears consecutively for at least three times.
    Consecutive Numbers - LeetCode
    https://leetcode.com/problems/consecutive-numbers/description/
    Consecutive Numbers - LeetCode
    notion image
    세 번 이상 연속으로 나타나는 모든 숫자를 찾아보세요. 결과 테이블을 순서에 상관없이 반환하세요.
     

    내가 작성한 쿼리

    MySQL, Oracle

    /* 자기 자신(id)과 다음 2개 행(id+1, id+2)의 num 값을 비교해서 3개가 모두 같으면 그 숫자를 결과에 포함 */ SELECT DISTINCT L1.num AS ConsecutiveNums FROM Logs L1 JOIN Logs L2 ON L2.id = L1.id + 1 JOIN Logs L3 ON L3.id = L1.id + 2 WHERE L1.num = L2.num AND L2.num = L3.num;
    Share article
    Contents
    내가 작성한 쿼리

    stupefyee

    RSS·Powered by Inblog