Home >Database >Mysql Tutorial >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)
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)
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
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!