mysql累积聚合原理与用法实例分析
程序员文章站
2022-06-02 09:28:32
本文实例讲述了mysql累积聚合原理与用法。分享给大家供大家参考,具体如下:
累积聚合为聚合从序列内第一个元素到当前元素的数据,如为每个员工返回每月开始到现在累积的订单数量和平均订单...
本文实例讲述了mysql累积聚合原理与用法。分享给大家供大家参考,具体如下:
累积聚合为聚合从序列内第一个元素到当前元素的数据,如为每个员工返回每月开始到现在累积的订单数量和平均订单数量
行号问题有两个解决方案,分别是为使用子查询和使用连接。子查询的方法通常比较直观,可读性强。但是在要求进行聚合时,子查询需要为每个聚合扫描一次数据,而连接方法通常只需要扫描一次就可以得到结果。下面的查询使用连接来得到结果
select a.empid, a.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 <= a.ordermonth group by a.empid,a.ordermonth,a.qty order by a.empid,a.ordermonth
如果只是查询2015年的累积订单,可以加上以where条件
where date_format(a.ordermonth,'%y')='2015' and date_format(b.ordermonth,'%y')='2015'
运行结果如下
此外可能还需要筛选数据,例如只需要返回每个员工到达某一目标之前每月订单的情况。这里假设统计每个员工的合计订单数量达到1000之前的累积情况。
这里可以使用having过滤器来完成查询
select a.empid, a.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 <= a.ordermonth where date_format(a.ordermonth,'%y')='2015' and date_format(b.ordermonth,'%y')='2015' group by a.empid,a.ordermonth,a.qty having total<1000 order by a.empid,a.ordermonth
这里并没有统计到达到1000时该月的情况,如果要进行统计,则情况又有点复杂。如果指定了total <= 1000,则只有该月订单数量正好为1000才进行统计,否则不会对该月进行统计。因此这个问题的过滤,可以从另外一个方面来考虑。当累积累积订单小于1000时,累积订单与上个月的订单之差是小于1000的,同时也能对第一个订单数量超过1000的月份进行统计。故该解决方案的sql语句如下
select a.empid, a.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 <= a.ordermonth where date_format(a.ordermonth,'%y')='2015' and date_format(b.ordermonth,'%y')='2015' group by a.empid,a.ordermonth,a.qty having total-a.qty < 1000 order by a.empid,a.ordermonth
运行结果如下
如果只想返回达到累积订单数为1000的当月数据,不返回之前的月份,则可以对上述sql语句
进一步过滤,再添加累积订单数量大于等于1000的条件。该问题的sql语句如下,
select a.empid, a.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 <= a.ordermonth where date_format(a.ordermonth,'%y')='2015' and date_format(b.ordermonth,'%y')='2015' group by a.empid,a.ordermonth,a.qty having total-a.qty < 1000 and total >= 1000 order by a.empid,a.ordermonth
运行结果如下