inblog logo
|
silver
    SQL문제풀기

    [SQL문제풀기] Biggest Single Number

    silver's avatar
    silver
    Nov 03, 2025
    [SQL문제풀기] Biggest Single Number
    Contents
    문제MySQL

    문제

    Biggest Single Number - LeetCode
    Can you solve this real interview question? Biggest Single Number - Table: MyNumbers +-------------+------+ | Column Name | Type | +-------------+------+ | num | int | +-------------+------+ This table may contain duplicates (In other words, there is no primary key for this table in SQL). Each row of this table contains an integer.   A single number is a number that appeared only once in the MyNumbers table. Find the largest single number. If there is no single number, report null. The result format is in the following example.   Example 1: Input: MyNumbers table: +-----+ | num | +-----+ | 8 | | 8 | | 3 | | 3 | | 1 | | 4 | | 5 | | 6 | +-----+ Output: +-----+ | num | +-----+ | 6 | +-----+ Explanation: The single numbers are 1, 4, 5, and 6. Since 6 is the largest single number, we return it. Example 2: Input: MyNumbers table: +-----+ | num | +-----+ | 8 | | 8 | | 7 | | 7 | | 3 | | 3 | | 3 | +-----+ Output: +------+ | num | +------+ | null | +------+ Explanation: There are no single numbers in the input table so we return null.
    Biggest Single Number - LeetCode
    https://leetcode.com/problems/biggest-single-number/description/?envType=study-plan-v2&envId=top-sql-50
    Biggest Single Number - LeetCode

    MySQL

    내가 작성한 정답

    select max(num) num from MyNumbers where num in (select num from MyNumbers group by num having count(num) =1);
    notion image

    내가 작성한 오답

    select num from MyNumbers group by num having count(num) = 1 order by 1 desc limit 1;
    MyNumbers 테이블에는 단 한 번 등장한 숫자가 없음
    → 그래서 group by + having count(num) = 1 조건을 만족하는 row 자체가 없음
    → 즉 결과 집합이 비어 있음(empty set)
    ✔ 하지만 빈 결과집합은 NULL을 반환하지 않는다.
    → 그냥 “아무 행도 없음”이기 때문에, MySQL은 결과를 출력하지 않을 뿐
    → NULL을 자동으로 출력해주지 않음
    notion image
    → 빈 결과일 때 NULL을 반환하고 싶으면 서브쿼리 사용 + COALESCE 하면 됨.
    // 이건 정답 select ( select num from MyNumbers group by num having count(num) = 1 order by num desc limit 1 ) as num;
     
    Share article

    silver

    RSS·Powered by Inblog