본문 바로가기
Data Science/SQL

[SQL/오답] 가장 많은 주문을 한 고객 찾기: HAVING의 한계와 ORDER BY + LIMIT의 효율성 (LeetCode586 Easy)

by 에르모사 쩐뉴 2026. 2. 6.

586. Customer Placing the Largest Number of Orders; ORDER BY, LIMIT

1. Problem

주문 기록이 담긴 테이블에서 가장 많은 주문을 기록한 고객의 번호를 찾아야 한다.

  • 핵심 과제: 고객별로 주문 건수를 집계하고, 그중 최댓값을 가진 고객 한 명만 정확히 골라내는 것이다. (문제 조건상 우승자는 항상 1명이다.)

2. Solution: 그룹화와 정렬을 이용한 1위 추출

GROUP BY로 고객별 건수를 센 뒤, 내림차순 정렬과 LIMIT을 조합하여 최상위 데이터를 가져온다.

3. Takeaway: 왜 HAVING MAX(COUNT(...))는 작동하지 않는가? (객관적 분석)

  • 집계 함수의 중첩 불가능 (유진 님의 오답 분석):
    • 오답: HAVING MAX(COUNT(order_number))
    • 원인 1: SQL 표준에서 MAX(COUNT(*))와 같은 집계 함수의 중첩은 허용되지 않는다. COUNT는 그룹화된 결과에 대한 집계이고, MAX는 그 결과 집합들 중에서 다시 집계를 내야 하므로 논리적 단계가 섞이게 된다.
    • 원인 2: HAVING 절은 WHERE 절과 마찬가지로 결과가 **참(True) 또는 거짓(False)**인 조건식이 와야 한다. 단순히 MAX 값을 적는 것은 조건이 아니므로 에러가 발생한다.
  • LIMIT 1의 객관적 우수성:
    • 최댓값을 찾기 위해 서브쿼리를 복잡하게 짜는 것보다, 전체를 정렬(ORDER BY)한 뒤 가장 위에 있는 하나(LIMIT 1)를 집어내는 것이 쿼리 가독성 면에서 훨씬 우수하다.
    • 문제에서 "최댓값을 가진 고객이 정확히 한 명"이라고 명시했으므로, 이 방식이 가장 빠르고 정확한 해법이 된다.

Table: Orders

+-----------------+----------+
| Column Name     | Type     |
+-----------------+----------+
| order_number    | int      |
| customer_number | int      |
+-----------------+----------+
order_number is the primary key (column with unique values) for this table.
This table contains information about the order ID and the customer ID.
 

Write a solution to find the customer_number for the customer who has placed the largest number of orders.

The test cases are generated so that exactly one customer will have placed more orders than any other customer.

The result format is in the following example.

 

Example 1:

Input: 
Orders table:
+--------------+-----------------+
| order_number | customer_number |
+--------------+-----------------+
| 1            | 1               |
| 2            | 2               |
| 3            | 3               |
| 4            | 3               |
+--------------+-----------------+
Output: 
+-----------------+
| customer_number |
+-----------------+
| 3               |
+-----------------+
Explanation: 
The customer with number 3 has two orders, which is greater than either customer 1 or 2 because each of them only has one order. 
So the result is customer_number 3.

 

1. 모범답안

SELECT customer_number 
FROM Orders
GROUP BY customer_number
ORDER BY COUNT(order_number) DESC
LIMIT 1;                                  # 꼭 리밋걸기

 

2. 나의 오답

SELECT customer_number
FROM Orders
GROUP BY customer_number
HAVING MAX(COUNT(order_number));   #HAVING은 T/F Boolean 값을 갖는 형태여야 함. 집계함수를 중첩해서 쓸 수 없음