Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ Have a good contributing!
- [1174. Immediate Food Delivery II](./leetcode/medium/1174.%20Immediate%20Food%20Delivery%20II.sql)
- [1193. Monthly Transactions I](./leetcode/medium/1193.%20Monthly%20Transactions%20I.sql)
- [1204. Last Person to Fit in the Bus](./leetcode/medium/1204.%20Last%20Person%20to%20Fit%20in%20the%20Bus.sql)
- [1321. Restaurant Growth](./leetcode/medium/1321.%20Restaurant%20Growth.sql)
- [1341. Movie Rating](./leetcode/medium/1341.%20Movie%20Rating.sql)
- [1907. Count Salary Categories](./leetcode/medium/1907.%20Count%20Salary%20Categories.sql)
- [1934. Confirmation Rate](./leetcode/medium/1934.%20Confirmation%20Rate.sql)
Expand Down
50 changes: 50 additions & 0 deletions leetcode/medium/1321. Restaurant Growth.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
Question 1321. Restaurant Growth
Link: https://leetcode.com/problems/restaurant-growth/description/?envType=study-plan-v2&envId=top-sql-50

Table: Customer

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| customer_id | int |
| name | varchar |
| visited_on | date |
| amount | int |
+---------------+---------+
In SQL,(customer_id, visited_on) is the primary key for this table.
This table contains data about customer transactions in a restaurant.
visited_on is the date on which the customer with ID (customer_id) has visited the restaurant.
amount is the total paid by a customer.


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

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 the result table ordered by visited_on in ascending order.
*/

WITH visited_dates AS (
SELECT visited_on + INTERVAL '6 days' AS dates
FROM Customer
GROUP BY visited_on
)

SELECT DISTINCT
c.visited_on,
(
SELECT SUM(c1.amount)
FROM Customer AS c1
WHERE c1.visited_on BETWEEN c.visited_on - INTERVAL '6 days' AND c.visited_on
) AS amount,
(
SELECT ROUND(SUM(c2.amount)::NUMERIC / 7, 2)
FROM Customer AS c2
WHERE c2.visited_on BETWEEN c.visited_on - INTERVAL '6 days' AND c.visited_on
) AS average_amount
FROM Customer AS c
LEFT JOIN
visited_dates AS v
ON c.visited_on = v.dates
WHERE v.dates IS NOT NULL