1321. Restaurant Growth
https://leetcode.com/problems/restaurant-growth/
Restaurant Growth - LeetCode
Can you solve this real interview question? Restaurant Growth - Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
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.
# 당신은 식당 주인이고 가능한 확장을 분석하려고 합니다(매일 최소 한 명의 고객이 있을 것입니다).
# 고객이 7일 창(즉, 현재 날짜 + 6일 전)에 지불한 금액의 이동 평균을 계산하는 SQL 쿼리를 작성합니다.
정답 코드
1. WITH문
# 1
WITH cus_table AS -- 방문일별 총 금액
(SELECT visited_on, SUM(amount) AS amount
FROM Customer
GROUP BY visited_on)
SELECT c1.visited_on,
ROUND(SUM(c2.amount),2) as amount,
ROUND(AVG(c2.amount),2) as average_amount
FROM cus_table c1 JOIN cus_table c2
ON DATEDIFF(c1.visited_on, c2.visited_on ) BETWEEN 0 AND 6
GROUP BY 1
HAVING count(distinct c2.visited_on) = 7
ORDER BY 1
2. 서브쿼리
# 2
SELECT a.visited_on AS visited_on, SUM(b.day_sum) AS amount,
ROUND(AVG(b.day_sum), 2) AS average_amount
FROM
(SELECT visited_on, SUM(amount) AS day_sum FROM Customer GROUP BY visited_on ) a,
(SELECT visited_on, SUM(amount) AS day_sum FROM Customer GROUP BY visited_on ) b
WHERE DATEDIFF(a.visited_on, b.visited_on) BETWEEN 0 AND 6
GROUP BY a.visited_on
HAVING COUNT(b.visited_on) = 7
'🛠️Skill > CodingTest' 카테고리의 다른 글
[leetcode] 601. Human Traffic of Stadium / 연속된 숫자 3개 이상 (0) | 2023.04.19 |
---|---|
[leetcode] 262. Trips and Users / 취소 비율 구하기 (0) | 2023.04.17 |
[leetcode] 1341. Movie Rating / 평점 가장 많이 남긴 사람, 평점이 가장 높은 영화 (0) | 2023.03.27 |
[leetcode] 1204. Last Person to Fit in the Bus / 버스 마지막 승객 구하기 (0) | 2023.03.09 |
[leetcode] 1174. Immediate Food Delivery II / 즉시배송할 수 있는 주문비율 (0) | 2023.03.08 |
댓글