Growth ๐ŸŒณ/Practice ๐Ÿ’ป

[LeetCode] 586. Customer Placing the Largest Number of Orders

์ธ” 2022. 9. 28. 22:46

๐Ÿ“ข ๋ณธ ํฌ์ŠคํŒ…์— ํ™œ์šฉ๋˜๋Š” ๊ธฐ๋ณธ ๋ฌธ์ œ ๋ฐ ์ž๋ฃŒ ์ถœ์ฒ˜๋Š”

       ๋ฆฌํŠธ์ฝ”๋“œ Problems, https://leetcode.com/problemset/all/์ž„์„ ๋ฐํž™๋‹ˆ๋‹ค.


โ–  ๋ฌธ์ œ

https://leetcode.com/problems/customer-placing-the-largest-number-of-orders/

 

Customer Placing the Largest Number of Orders - 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

Table: Orders

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

 

Write an SQL query 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 query 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.

 

Follow up: What if more than one customer has the largest number of orders, can you find all the customer_number in this case?


โ–  ํ’€์ด

  ๋ฌธ์ œ ์š”๊ตฌ์‚ฌํ•ญ  

์ฃผ๋ฌธ(order_number)๊ฑด์ˆ˜๊ฐ€ ๊ฐ€์žฅ ๋งŽ์€ ๊ณ ๊ฐ ๋ฒˆํ˜ธ(customer_number)๋ฅผ ์ถœ๋ ฅํ•ด๋ผ

> ๊ณ ๊ฐ๋ฒˆํ˜ธ๋ณ„๋กœ ์ฃผ๋ฌธ๊ฑด์ˆ˜๋ฅผ countํ•ด์ฃผ๊ณ  ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•ด์„œ ์ฃผ๋ฌธ๊ฑด์ˆ˜๊ฐ€ ๊ฐ€์žฅ ๋งŽ์€ ๊ณ ๊ฐ๋ฒˆํ˜ธ๋ฅผ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค.

>> FROM์ ˆ์˜ ์„œ๋ธŒ์ฟผ๋ฆฌ, LIMIT ํ™œ์šฉ

SELECT customer_number
 FROM (SELECT customer_number, count(*)
        FROM Orders
        GROUP BY customer_number
        ORDER BY 2 DESC) a
 LIMIT 1;