Growth ๐ŸŒณ/Practice ๐Ÿ’ป

[LeetCode] 1321. Restaurant Growth

์ธ” 2023. 6. 17. 18:31

 

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

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


โœ” ๋ฌธ์ œ

https://leetcode.com/problems/restaurant-growth/description/

 

Restaurant Growth - LeetCode

Can you solve this real interview question? Restaurant Growth - Table: Customer +---------------+---------+ | Column Name | Type | +---------------+---------+ | customer_id | int | | name | varchar | | visited_on | date | | amount | int | +---------------+

leetcode.com

Table : Customer

You are the restaurant owner and you want to analyze a possible expansion (there will be at least one customer every day).

Write an SQL query to compute the moving average of how much the customer paid in a seven days window (i.e., current day + 6 days before). average_amount should be rounded to two decimal places.

Return result table ordered by visited_on in ascending order.

The query result format is in the following example.


โœ” ํ’€์ด

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

๋งค์ผ ์ผ์ฃผ์ผ ๊ฐ„ ๋ˆ„์ ๋œ ๋งค์ถœ๊ณผ ๋ˆ„์  ํ‰๊ท  ๋งค์ถœ์„ ๊ตฌํ•ด์•ผ ํ•œ๋‹ค.

 

โ‘  ์ผ์ž๋ณ„ ๋งค์ถœ์„ ๊ตฌํ•œ๋‹ค.

     ์ผ์ž๋ณ„ ๋งค์ถœ = ํ•ด๋‹น ์ผ์ž์— ๋ฐฉ๋ฌธํ•œ ๊ณ ๊ฐ๋ณ„ amount์˜ ํ•ฉ

โ‘ก ๊ธฐ์ค€์ผ์ž๋ณ„๋กœ {๊ธฐ์ค€์ผ์ž + 6์ผ} (์ด 7์ผ) ๋งค์ถœ๊ณผ ํ‰๊ท  ๋งค์ถœ์„ ๊ตฌํ•œ๋‹ค → ์ด๋™ํ‰๊ท ๋งค์ถœ

โ‘ข ์ •๋ ฌํ•œ๋‹ค.

 

- ๊ธฐ์ค€์ผ์ž ๊ธฐ์ค€ ์ผ์ฃผ์ผ๋‹จ์œ„ ๋งค์ถœ์„ ๊ตฌํ•ด์•ผ ํ•˜๋ฏ€๋กœ โ‘ ์—์„œ ๊ตฌํ•œ sum(amount)์— ์œˆ๋„์šฐ ํ•จ์ˆ˜์˜ ์ง‘๊ณ„ํ•จ์ˆ˜๋ฅผ ์ ์šฉํ•˜๊ณ  ๊ธฐ์ค€์ผ์ž์—์„œ 6์ผ์ „๋ถ€ํ„ฐ์˜ sum(amount)๋ฅผ ๋”ํ•ด์ฃผ๋Š” ์‹์„ ๋งŒ๋“ ๋‹ค.

- ์ด๋™ํ‰๊ท ๋งค์ถœ์€ ์œ„์—์„œ ๊ตฌํ•œ amount์˜ ํ‰๊ท ๊ฐ’์„ ๊ตฌํ•œ๋‹ค.

 

๋‹จ, ์ผ์ฃผ์ผ ๋งค์ถœ์˜ ํ•ฉ์ด๋ฏ€๋กœ ์ตœ์†Œ ์ผ์ฃผ์ผ ๋ฐ์ดํ„ฐ๊ฐ€ ๋ˆ„์ ๋˜์–ด ์žˆ๋Š” ์ผ์ž๋ถ€ํ„ฐ ๊ธฐ์ค€์ผ์ž๋กœ ์ ์šฉํ•ด์•ผ ํ•œ๋‹ค.

SELECT visited_on, amount, average_amount
 FROM (
        SELECT visited_on,
               SUM(SUM(amount)) OVER (ORDER BY visited_on ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS amount,
               ROUND(AVG(SUM(amount)) OVER (ORDER BY visited_on ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), 2) AS average_amount
        FROM Customer
        GROUP BY 1) T
 WHERE DATE_SUB(visited_on, INTERVAL 6 DAY) IN (SELECT visited_on FROM Customer)

'Growth ๐ŸŒณ > Practice ๐Ÿ’ป' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Leet code] 1173. Immediate Food Delivery I  (0) 2023.08.03
[Leet code] 1164. Product Price at a Given Date  (0) 2023.07.17
[LeetCode] 1158. Market Analysis I  (0) 2023.06.08
[LeetCode] 1070. Product Sales Analysis III  (0) 2023.05.22
[LeetCode] 1045. Customers Who Bought All Products  (0) 2023.05.18