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

MySQL index usage instructions (single-column index and multi-column index)

1. Single column index Choosing which columns to ...

MySQL trigger syntax and application examples

This article uses examples to illustrate the synt...

Detailed usage of Linux text search command find

The find command is mainly used to find directori...

How to position the header at the top using CSS sticky layout

Application scenarios: One of the new requirement...

MySQL DATE_ADD and ADDDATE functions add a specified time interval to a date

MySQL DATE_ADD(date,INTERVAL expr type) and ADDDA...

A few front-end practice summaries of Alipay's new homepage

Of course, it also includes some personal experien...

Detailed explanation of WeChat Mini Program official face verification

The mini program collected user personal informat...

JavaScript css3 to implement simple video barrage function

This article attempts to write a demo to simulate...

How to migrate sqlite to mysql script

Without further ado, I will post the code for you...

Write a dynamic clock on a web page in HTML

Use HTML to write a dynamic web clock. The code i...

Vue+spring boot realizes the verification code function

This article example shares the specific code of ...

Windows Server 2019 IIS10.0+PHP(FastCGI)+MySQL Environment Construction Tutorial

Preparation 1. Environmental Description: Operati...

In-depth explanation of MySQL learning engine, explain and permissions

engine Introduction Innodb engine The Innodb engi...