前述
窗口函数相关知识推荐阅读:
通俗易懂的学会:SQL窗口函数
窗口函数rows between 、range between的使用
MySQL中的DATEDIFF()函数
mysql data类型的加减
常用函数:
- ROUND() 函数:用于将数值四舍五入到指定的小数位数。
- FLOOR() 函数:用于将数值向下取整,去掉小数部分,保留整数部分。
- CEIL() 或 CEILING() 函数:用于将数值向上取整,进位到最接近的整数。
题目描述
leetcode 题目:1321. 餐馆营业额变化增长
思路
- 先按照日期分组
- 统计总额,平均额
写法一:自连接
思想:
- 先取出结果集中的所有visited_on字段,
- 再在其后连接其余字段并分组统计总额,平均额
select B.visited_on,
sum(C.amount) as amount,
round(sum(C.amount)/7, 2) as average_amount
from (
select distinct date_add(A.visited_on, interval 6 day) as visited_on
from Customer A
where date_add(A.visited_on, interval 6 day) <= (
select B.visited_on
from Customer B
order by B.visited_on desc
limit 1
)) B
join Customer C
on datediff(B.visited_on, C.visited_on) between 0 and 6
group by B.visited_on
order by B.visited_on
date_add(A.visited_on, interval 6 day) # 在A.visited_on的日期基础上,加上6天
解析:B表是为了得到结果集当中的visited_on字段的所有值
将B表连接其余字段:
最后再按照visited_on字段分组(group by B.cisited_on),并用聚合函数SUM()计算总额及平均额等。
写法二:自连接
select C.visited_on,
sum(D.amount) as amount,
round(sum(D.amount)/7, 2) as average_amount
from(
select distinct A.visited_on -- C 表为只取出结果集当中的visited_on字段的所有值
from Customer A
where A.visited_on >= (
select min(B.visited_on)
from Customer B
) + 6) C
left join Customer D
on datediff(C.visited_on, D.visited_on) between 0 and 6
group by C.visited_on
order by C.visited_on
写法三:窗口函数
学习题解中大佬的写法:整理两种主流的解决办法【自连接、窗口函数】,并部分改进
引用【窗口函数rows between 、range between的使用】的总结:
rows between 控制窗口函数的范围,使用rows between可以根据自己的需求任意的控制窗口函数的范围
- UNBOUNDED :不受控的,无限的;
- PRECEDING : 在…之前;
- FOLLOWING: 在…之后;
select distinct visited_on,
sum_amount as amount,
round(sum_amount/7, 2) as average_amount
from (
select visited_on, sum(amount) over(order by visited_on range interval 6 day preceding) as sum_amount
from Customer) t
-- 最后手动地从第7天开始
where datediff(visited_on, (select MIN(visited_on) from Customer)) >= 6