mysql滑动聚合/年初至今聚合原理与用法实例分析

2022-10-09,,,,

本文实例讲述了mysql滑动聚合/年初至今聚合原理与用法。分享给大家供大家参考,具体如下:

滑动聚合是按顺序对滑动窗口范围内的数据进行聚合的操作。下累积聚合不同,滑动聚合并不是统计开始计算的位置到当前位置的数据。

这里以统计最近三个月中员工第月订单情况为例来介绍滑动聚合。

滑动聚合和累积聚合解决方案的主要区别在于连接的条件不同。滑动聚合条件不再是b.ordermonth <= a.ordermonth,而应该是b.ordermonth大于前三个月的月份,并且小于当前月份。因此滑动聚合的解决方案的sql语句如下

select
 a.empid,
 date_format(a.ordermonth, '%y-%m') as ordermonth,
 a.qty as thismonth,
 sum(b.qty) as total,
 cast(avg(b.qty) as decimal(5,2)) as avg
from emporders a
inner join emporders b
 on a.empid=b.empid
 and b.ordermonth > date_add(a.ordermonth, interval -3 month)
 and b.ordermonth <= a.ordermonth
where date_format(a.ordermonth,'%y')='2015' and date_format(b.ordermonth,'%y')='2015'
group by a.empid,date_format(a.ordermonth, '%y-%m'),a.qty
order by a.empid,a.ordermonth

运行结果如下

该解决方案返回的是三个月为一个周期的滑动聚合,但是每个用户包含前两个月并且未满3个月的聚合。如果只希望返回满3个月的聚合,不返回未满3个月的聚合,可以使用having过滤器进行过滤,过滤的条件为min(b.ordermonth)=date_add(a.ordermonth, interval -2 month),例如

select
 a.empid,
 a.ordermonth as ordermonth,
 a.qty as thismonth,
 sum(b.qty) as total,
 cast(avg(b.qty) as decimal(5,2)) as avg
from emporders a
inner join emporders b
 on a.empid=b.empid
 and b.ordermonth > date_add(a.ordermonth, interval -3 month)
 and b.ordermonth <= a.ordermonth
where date_format(a.ordermonth,'%y')='2015' and date_format(b.ordermonth,'%y')='2015' and a.empid=1
group by a.empid,date_format(a.ordermonth, '%y-%m'),a.qty
having min(b.ordermonth)=date_add(a.ordermonth, interval-2 month)
order by a.empid,a.ordermonth

运行结果如下

年初至今聚合和滑动聚合类似,不同的地方仅在于统计的仅为当前一年的聚合。唯一的区别体现在下限的开始位置上。在年初至今的问题中,下限为该年的第一天,而滑动聚合的下限为n个月的第一天。因此,年初至今的问题的解决方案如下图所示,得到的结果

select
 a.empid,
 date_format(a.ordermonth, '%y-%m') as ordermonth,
 a.qty as thismonth,
 sum(b.qty) as total,
 cast(avg(b.qty) as decimal(5,2)) as avg
from emporders a
inner join emporders b
  on a.empid=b.empid
  and b.ordermonth >= date_format(a.ordermonth, '%y-01-01')
  and b.ordermonth <= a.ordermonth
  and date_format(b.ordermonth,'%y')='2015'
group by a.empid,a.ordermonth,a.qty
order by a.empid,a.ordermonth

运行结果如下

《mysql滑动聚合/年初至今聚合原理与用法实例分析.doc》

下载本文的Word格式文档,以方便收藏与打印。