Home > Database > Mysql Tutorial > How to Efficiently Group Time-Series Data by Week in MySQL?

How to Efficiently Group Time-Series Data by Week in MySQL?

DDD
Release: 2024-12-13 06:02:10
Original
643 people have browsed it

How to Efficiently Group Time-Series Data by Week in MySQL?

Grouping Data by Week in MySQL

When dealing with time-series data, it's often useful to group records by week. While Oracle offers built-in functions for this purpose, MySQL requires a slightly different approach.

Weekday Truncation

To truncate a timestamp to midnight on the previous Sunday, as done in Oracle using TRUNC(timestamp,'DY'), MySQL does not offer a direct equivalent. However, you can emulate this behavior using the following expression:

DATE_ADD(DATE(timestamp), INTERVAL (DAYOFWEEK(timestamp) - 7) DAY)
Copy after login

This expression subtracts the current day of the week from the timestamp, resulting in a date corresponding to the previous Sunday.

Month Truncation

For truncating a timestamp to midnight on the first day of the month, MySQL provides the straightforward DATE_FORMAT(timestamp, '%Y-%m-01') function, which is similar to Oracle's TRUNC(timestamp,'MM').

Week Truncation

Although MySQL has the WEEK(timestamp) function, it returns the week number within the year. To group by complete weeks, rather than week numbers, you can combine YEAR(timestamp) and WEEK(timestamp) in the SELECT and GROUP BY clauses, as follows:

SELECT YEAR(timestamp), WEEK(timestamp)
FROM ...
WHERE ...
GROUP BY YEAR(timestamp), WEEK(timestamp)
Copy after login

Alternatively, you can use the YEARWEEK(mysqldatefield) function, which returns the combined year and week number. However, its output may not be as user-friendly as the YEAR(timestamp) / WEEK(timestamp) approach.

Note: For aggregating by complete weeks, including those that span over January 1st, consider using YEARWEEK(mysqldatefield) with the second argument (mode) set to either 0 or 2.

Example:

The following query groups data by complete weeks:

SELECT YEARWEEK(timestamp, 0) AS week_number, SUM(value) AS total
FROM data
WHERE ...
GROUP BY week_number
Copy after login

The above is the detailed content of How to Efficiently Group Time-Series Data by Week in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template