原文链接:https://blog.csdn.net/weixin_45638528/article/details/130229603
移动求和的窗口函数——连续n个数据求和
sum(字段1) over (partition by 字段2 order by 字段3 rows n preceding)
LEECODE 1321 餐馆营业额变化增长
表: Customer
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| customer_id | int |
| name | varchar |
| visited_on | date |
| amount | int |
+---------------+---------+
(customer_id, visited_on) 是该表的主键。
该表包含一家餐馆的顾客交易数据。
visited_on 表示 (customer_id) 的顾客在 visited_on 那天访问了餐馆。
amount 是一个顾客某一天的消费总额。
你是餐馆的老板,现在你想分析一下可能的营业额变化增长(每天至少有一位顾客)。
写一条 SQL 查询计算以 7 天(某日期 + 该日期前的 6 天)为一个时间段的顾客消费平均值。average_amount 要 保留两位小数。
查询结果按 visited_on 排序。
查询结果格式的例子如下。
示例 1:
输入:
Customer 表:
+-------------+--------------+--------------+-------------+
| customer_id | name | visited_on | amount |
+-------------+--------------+--------------+-------------+
| 1 | Jhon | 2019-01-01 | 100 |
| 2 | Daniel | 2019-01-02 | 110 |
| 3 | Jade | 2019-01-03 | 120 |
| 4 | Khaled | 2019-01-04 | 130 |
| 5 | Winston | 2019-01-05 | 110 |
| 6 | Elvis | 2019-01-06 | 140 |
| 7 | Anna | 2019-01-07 | 150 |
| 8 | Maria | 2019-01-08 | 80 |
| 9 | Jaze | 2019-01-09 | 110 |
| 1 | Jhon | 2019-01-10 | 130 |
| 3 | Jade | 2019-01-10 | 150 |
+-------------+--------------+--------------+-------------+
输出:
+--------------+--------------+----------------+
| visited_on | amount | average_amount |
+--------------+--------------+----------------+
| 2019-01-07 | 860 | 122.86 |
| 2019-01-08 | 840 | 120 |
| 2019-01-09 | 840 | 120 |
| 2019-01-10 | 1000 | 142.86 |
+--------------+--------------+----------------+
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/restaurant-growth
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答
1、首先按visited_on分组,先计算每个日期的总的amount
select visited_on, sum(amount) as amount from Customer group by visited_on;
2、对上面得出的表计算移动平均、移动求和
select visited_on, sum(amount) over (order by visited_on rows 6 preceding) as amount, avg(amount) over (order by visited_on rows 6 preceding) as average_amount from ( select visited_on,sum(amount) as amount from Customer group by visited_on) as a;
3、因为题目计算的是以7天为一个时间段的数据,上表我们得出的结果包含了不足7天的数据(如2019-01-01至2019-01-06),因此要进行筛选,筛选思路可以是 每个日期与列表最小间隔日期为6天
select visited_on,amount,round(average_amount,2) as average_amount from ( select visited_on, sum(amount) over (order by visited_on rows 6 preceding) as amount, avg(amount/1.0) over (order by visited_on rows 6 preceding) as average_amount from ( select visited_on,sum(amount) as amount from Customer group by visited_on ) as a ) as b where datediff(day, (select min(visited_on) from Customer), visited_on)>=6;
原文链接:https://blog.csdn.net/weixin_45638528/article/details/130229603
标签:01,求和,sum,amount,Leecode,2019,SQL,visited,select From: https://www.cnblogs.com/Dongmy/p/18120103