본문 바로가기

SQL/LeetCode

[SQL] Immediate Food Delivery II(LeetCode/Oracle)

안녕하세요!

 

이번 포스팅은 LeetCode에 있는 Immediate Food Delivery II 문제를 OracleDB로 풀어보려고 합니다!

 

(모든 문제는 Oracle로 풀이하겠습니다.)

 

1. 문제 링크 : https://leetcode.com/problems/immediate-food-delivery-ii/description/

 

2. 문제

Column name Type
delivery_id int
customer_id int
order_date date
customer_pref_delivery_date date
[문제] If the customer's preferred delivery date is the same as the order date, then the order is called immediate; otherwise, it is called scheduled.

The first order of a customer is the order with the earliest order date that the customer made. It is guaranteed that a customer has precisely one first order.

Write a solution to find the percentage of immediate orders in the first orders of all customers, rounded to 2 decimal places.

모든 고객의 첫 번째 주문에서 즉시 주문의 비율을 조회하는 문제입니다.

 

3. 제출 쿼리 및 설명

 

1) 고객 별로 주문일 순으로 순위를 매긴 리스트(컬럼명 : RK)를 생성합니다.

SELECT
    ORDER_DATE, 
    CUSTOMER_ID, 
    CUSTOMER_PREF_DELIVERY_DATE, 
    RANK() OVER(PARTITION BY CUSTOMER_ID ORDER BY ORDER_DATE) AS RK
FROM DELIVERY

최종) 1번 쿼리를 인라인 뷰로 활용해서 첫 번째 주문에서 즉시 주문 비율을 구합니다.

SELECT 
  ROUND(100 * SUM(CASE WHEN ORDER_DATE = CUSTOMER_PREF_DELIVERY_DATE THEN 1 ELSE 0 END)/COUNT(DISTINCT CUSTOMER_ID), 2) AS IMMEDIATE_PERCENTAGE
FROM (
  SELECT
    ORDER_DATE, CUSTOMER_ID, 
    CUSTOMER_PREF_DELIVERY_DATE, 
    RANK() OVER(PARTITION BY CUSTOMER_ID ORDER BY ORDER_DATE) AS RK
  FROM DELIVERY
)
WHERE RK = 1