Growth ๐ŸŒณ/Practice ๐Ÿ’ป

[Leet code] 1174. Immediate Food Delivery II

์ธ” 2023. 9. 15. 13:49

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

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


โœ”๋ฌธ์ œ

https://leetcode.com/problems/immediate-food-delivery-ii/description/

 

Immediate Food Delivery II - LeetCode

Can you solve this real interview question? Immediate Food Delivery II - Table: Delivery +-----------------------------+---------+ | Column Name | Type | +-----------------------------+---------+ | delivery_id | int | | customer_id | int | | order_date | d

leetcode.com

Table : Delivery

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.

 

( …์ค‘๋žต )


โœ” ํ’€์ด

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

 

์ฒซ ์ฃผ๋ฌธ ์ด๋ ฅ์— ํ•ด๋‹นํ•˜๋Š” ๊ณ ๊ฐ์ค‘ ์„ ํ˜ธํ•˜๋Š” ๋ฐฐ์†ก ์ผ์ž์— ์ฃผ๋ฌธ์„ ๋ฐ›์€ '์ฆ‰์‹œ ์ฃผ๋ฌธ'์— ํ•ด๋‹นํ•˜๋Š” ๊ณ ๊ฐ์˜ ๋น„์œจ์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

 

· ์ „์ฒด๊ฐ€ ๋  ์ฒซ ์ฃผ๋ฌธ์ด์—ˆ๋˜ ๋ฐ์ดํ„ฐ๋“ค์„ with์ ˆ๋กœ ์ž„์‹œ ํ…Œ์ด๋ธ”์„ ์‚ฌ์šฉํ•ด์„œ ์ถœ๋ ฅํ•ด์คฌ๋‹ค.

๊ณ ๊ฐ๋ณ„ ์ œ์ผ '์ฒซ๋ฒˆ์งธ ์ฃผ๋ฌธ' ์กฐ๊ฑด์€ ์ง‘๊ณ„ํ•จ์ˆ˜ MIN์„ ์‚ฌ์šฉํ•˜์—ฌ  WHERE์ ˆ ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉ.

 

· CASE์ ˆ์„ ์‚ฌ์šฉํ•ด์„œ '์ฆ‰์‹œ ์ฃผ๋ฌธ'(customer_pref = customer_pref_delivery_date)์ด๋ผ๋ฉด 1 ์•„๋‹ˆ๋ฉด 0์„ ๋ถ€์—ฌํ•˜๊ณ 

   SUM๊ฐ’์œผ๋กœ ๋น„์œจ์— ํ•ด๋‹นํ•˜๋Š” ๊ณ ๊ฐ์ˆ˜๋ฅผ ๊ตฌํ–ˆ๋‹ค.

 

· ๋ถ„๋ชจ COUNT(customer_id) ์—์„œ ๋Š” ord_1st ์—์„œ ์ด๋ฏธ ๊ณ ๊ฐ๋ณ„ ์ฒซ๋ฒˆ์งธ ์ฃผ๋ฌธ์ด๋ ฅ์„ ๋ฝ‘์•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ฐ์ดํ„ฐ์ƒ ์ค‘๋ณต๊ฐ’์ด ์—†์œผ๋ฏ€๋กœ DISTINCT๋Š” ์ ์šฉํ•˜์ง€ ์•Š์•˜๋‹ค.

WITH ord_1st AS (
    SELECT delivery_id, customer_id, order_date, customer_pref_delivery_date
     FROM Delivery D1
     WHERE order_date = (SELECT MIN(order_date)
                          FROM Delivery
                          WHERE customer_id = D1.customer_id
                          GROUP BY customer_id)
     )

SELECT ROUND(
        SUM(CASE WHEN order_date = customer_pref_delivery_date THEN 1 ELSE 0 END) 
        / COUNT(customer_id) * 100 
        , 2) AS immediate_percentage
 FROM ord_1st