본문 바로가기
Data Analysis/Query

리트코드 : 586. Customer Placing the Largest Number of Orders

by 베짱이28호 2024. 4. 14.

리트코드 : 586. Customer Placing the Largest Number of Orders


문제

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.


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

문제 풀이

MySQL

SELECT CUSTOMER_NUMBER
FROM ORDERS
GROUP BY CUSTOMER_NUMBER
HAVING COUNT(ORDER_NUMBER) = (
    SELECT MAX(CNT)
    FROM (SELECT COUNT(ORDER_NUMBER) AS CNT FROM ORDERS GROUP BY CUSTOMER_NUMBER) AS TEMP
    )
  • GROUP BY에서 ORDER 수를 계산을 한다.
  • 계산한 ORDER 수의 최대값을 HAVING 조건에 걸어서 뽑아주기.

Pandas

import pandas as pd

def largest_orders(orders: pd.DataFrame) -> pd.DataFrame:

    if orders.empty:
        return pd.DataFrame({'customer_number':[]})

    temp = orders.groupby('customer_number').size().reset_index(name = 'count')
    max_count = temp[temp['count'] == max(temp['count'])]

    answer = max_count.merge(orders,on='customer_number')
    return answer[['customer_number']].head(1)

def largest_orders(orders: pd.DataFrame) -> pd.DataFrame:
    return orders['customer_number'].mode().to_frame()
  • 카운팅을 통해서 최빈값 찾기.
    • 밑에거처럼 바꾸는 방법도 있음....

코멘트

  • .

댓글