From 733145f9e70ae82263d687dec53819cecf898b71 Mon Sep 17 00:00:00 2001 From: ivanbyone Date: Wed, 9 Jul 2025 12:41:06 +0300 Subject: [PATCH] task: #1321 --- README.md | 1 + leetcode/medium/1321. Restaurant Growth.sql | 50 +++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 leetcode/medium/1321. Restaurant Growth.sql diff --git a/README.md b/README.md index 959d487..75fd7a5 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/leetcode/medium/1321. Restaurant Growth.sql b/leetcode/medium/1321. Restaurant Growth.sql new file mode 100644 index 0000000..8378877 --- /dev/null +++ b/leetcode/medium/1321. Restaurant Growth.sql @@ -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