zoukankan      html  css  js  c++  java
  • 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
    

    运行结果如下

  • 相关阅读:
    Linux 内核中的 Device Mapper 机制
    阿里云 Angular 2 UI框架 NG-ZORRO介绍
    Docker容器 暴露多个端口
    修改docker容器的端口映射
    Ubuntu Docker安装
    Docker容器技术的PaaS云平台架构设计***
    scala 学习笔记三 闭包
    scala 学习笔记二 方法与函数
    scala 学习笔记一 列表List
    Python3 写Windows Service服务程序
  • 原文地址:https://www.cnblogs.com/chenqionghe/p/4679750.html
Copyright © 2011-2022 走看看