mysql累积聚合原理与用法实例分析
雪山飞猪 人气:0这篇文章主要介绍了mysql累积聚合原理与用法,结合实例形式分析了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
运行结果如下
希望本文所述对大家MySQL数据库计有所帮助。
加载全部内容