๐ข ๋ณธ ํฌ์คํ ์ ํ์ฉ๋๋ ๊ธฐ๋ณธ ๋ฌธ์ ๋ฐ ์๋ฃ ์ถ์ฒ๋
๋ฆฌํธ์ฝ๋ Problems, https://leetcode.com/problemset/all/์์ ๋ฐํ๋๋ค.
โ ๋ฌธ์
https://leetcode.com/problems/restaurant-growth/description/
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 |