MySQL sliding aggregation/year-to-date aggregation principle and usage example analysis

MySQL sliding aggregation/year-to-date aggregation principle and usage example analysis

This article uses examples to illustrate the principles and usage of MySQL sliding aggregation/year-to-date aggregation. Share with you for your reference, the details are as follows:

Sliding aggregation is an operation that aggregates data within the sliding window range in sequence. Different from cumulative aggregation, sliding aggregation does not count the data from the starting position to the current position.

Here we take the example of counting the monthly orders of employees in the last three months to introduce sliding aggregation.

The main difference between the sliding aggregation and cumulative aggregation solutions lies in the different conditions for joining. The sliding aggregation condition is no longer b.ordermonth <= a.ordermonth, but b.ordermonth is greater than the months of the previous three months and less than the current month. Therefore, the SQL statement for the sliding aggregation solution is as follows

SELECT
 a.empid,
 DATE_FORMAT(a.ordermonth, '%Y-%m') AS ordermonth,
 a.qty AS this month,
 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

The results are as follows

This solution returns a sliding aggregation with a three-month period, but each user includes the aggregation of the previous two months and less than 3 months. If you only want to return the aggregates that are more than 3 months old, but not the aggregates that are less than 3 months old, you can use the HAVING filter to filter. The filtering condition is MIN(b.ordermonth)=DATE_ADD(a.ordermonth, INTERVAL -2 MONTH), for example

SELECT
 a.empid,
 a.ordermonth AS ordermonth,
 a.qty AS this month,
 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

The results are as follows

The year-to-date aggregation is similar to the sliding aggregation, except that only the aggregation for the current year is counted. The only difference is where the lower limit starts. In the year-to-date problem, the lower bound is the first day of the year, while the lower bound for the sliding aggregation is the first day of N months. Therefore, the solution to the year-to-date problem is shown below, and the results obtained

SELECT
 a.empid,
 DATE_FORMAT(a.ordermonth, '%Y-%m') AS ordermonth,
 a.qty AS this month,
 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

The results are as follows

Readers who are interested in more MySQL-related content can check out the following topics on this site: "MySQL query skills", "MySQL common functions summary", "MySQL log operation skills", "MySQL transaction operation skills summary", "MySQL stored procedure skills" and "MySQL database lock related skills summary"

I hope this article will be helpful to everyone's MySQL database design.

You may also be interested in:
  • Usage and performance optimization techniques of aggregate function count in MySQL
  • Detailed explanation of MySQL commonly used aggregate functions
  • How to add conditional expressions to aggregate functions in MySql
  • php+mysql open source XNA aggregation program released for download
  • Mysql cannot select non-aggregate columns
  • Analysis of MySQL query sorting and query aggregation function usage
  • Detailed explanation of MySQL single table query operation examples [syntax, constraints, grouping, aggregation, filtering, sorting, etc.]
  • Analysis of the principle and usage of MySQL continuous aggregation
  • Analysis of MySQL cumulative aggregation principle and usage examples

<<:  Detailed explanation of the problem that the space is not released after the Linux file is deleted

>>:  JavaScript MouseEvent Case Study

Recommend

Method to detect whether ip and port are connectable

Windows cmd telnet format: telnet ip port case: t...

Solution to the error when importing MySQL big data in Navicat

The data that Navicat has exported cannot be impo...

Introduction and use of Javascript generator

What is a generator? A generator is some code tha...

How to optimize MySQL performance through MySQL slow query

As the number of visits increases, the pressure o...

Tutorial on installing mysql5.7.18 on mac os10.12

I searched the entire web and found all kinds of ...

Web Design Tutorial (8): Web Page Hierarchy and Space Design

<br />Previous article: Web Design Tutorial ...

How to achieve 3D dynamic text effect with three.js

Preface Hello everyone, this is the CSS wizard - ...

The magic of tr command in counting the frequency of English words

We are all familiar with the tr command, which ca...

How to use mixins in Vue

Table of contents Preface How to use Summarize Pr...

Zabbix monitoring solution - the latest official version 4.4 [recommended]

Zabbix 2019/10/12 Chenxin refer to https://www.za...

14 Ways to Create Website Content That Engages Your Visitors

When I surf the Net, I often see web sites filled...

Why are the pictures on mobile web apps not clear and very blurry?

Why? The simplest way to put it is that pixels are...

How to use Navicat to export and import mysql database

MySql is a data source we use frequently. It is v...

MySQL Flush-List and dirty page flushing mechanism

1. Review The Buffer Pool will be initialized aft...