본문 바로가기

Algorithm/SQL

(SQL) - LeetCode (easy) 586. Customer Placing the Largest Number of Orders

반응형

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

 

Customer Placing the Largest Number of Orders - LeetCode

Can you solve this real interview question? Customer Placing the Largest Number of Orders - Table: Orders +-----------------+----------+ | Column Name | Type | +-----------------+----------+ | order_number | int | | customer_number | int | +---------------

leetcode.com

group by를 사용해보는 문제였습니다.

📕 풀이방법

📔 풀이과정

1. 의식의 흐름대로 customer_number를 group by로 묶어 주문 횟수를 세준 후 가상의 table을 만들어 거기서 가장 빈도 수가 많은 손님의 번호를 select

2. customer_number를 group by로 묶어 주문 횟수를 count(*)해 내림차순으로 정렬 후 가장 상위 row를 select


📕 Code

📔 MySQL

# 방법 1
select c.customer_number as customer_number from (
  select customer_number, count(customer_number) as ccnt from orders
  group by customer_number
  order by ccnt desc
  limit 1
) c

# 방법 2
select customer_number from orders
group by customer_number
order by count(*) desc
limit 1

📔 Oracle

SELECT customer_number
FROM (
    SELECT customer_number
    FROM orders
    GROUP BY customer_number
    ORDER BY COUNT(*) DESC
)
WHERE ROWNUM = 1;

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.