반응형
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.
- GROUP BY num 해서 각 숫자가 몇 번 나왔는지 세기
- HAVING COUNT(*) = 1 조건으로 딱 한 번만 등장한 숫자만 필터링
- MAX(num) 사용해서 가장 큰 숫자 하나만 추출
SELECT MAX(num) AS num
FROM MyNumbers
GROUP BY num
HAVING COUNT(*) = 1;
- GROUP BY num → 숫자별로 묶기
- HAVING COUNT(*) = 1 → 등장 횟수가 1번인 것만 남기기
- MAX(num) → 그 중에서 가장 큰 값 고르기
SELECT MAX(num) AS num -- subquery에서 맥시멈을 리턴
FROM (
SELECT num FROM MyNumbers GROUP BY num HAVING COUNT(*) = 1 -- num끼리 그룹핑 후 싱글 넘버 카운트 함
) AS nums
반응형
'Computer Science > SQL' 카테고리의 다른 글
SQL | LeetCode 1164. 모든 제품의 가격 구하기 (0) | 2025.05.13 |
---|---|
SQL | LeetCode 1731. 매니저 정보 구하기 (0) | 2025.05.13 |
SQL | LeetCode 550. Game Play Analysis IV (SQL 서브쿼리 사용) (0) | 2025.05.11 |
SQL | LeetCode 1174. 첫 주문 중 즉시 배송 비율 구하기 (1) | 2025.05.10 |
SQL | LeetCode 1193. 월별, 국가별 거래 요약 통계 구하기 (1) | 2025.05.09 |