简体   繁体   中英

Roll up daily data into monthly buckets in MySQL

Having trouble figuring out what seems like it should be a basic use case. Given a table of data written daily ('activity_date' date NOT NULL), roll up data into monthly buckets. GROUP BY docs and Date Type docs aren't much help and I can't find any tutorials on Google. There is a similar question here but I can't figure out how to make it work for my case. Is there a simple way to get what I need?

How about grouping by year and month?

SELECT YEAR(activity_date), MONTH(activity_date), COUNT(*)
FROM table
GROUP BY YEAR(activity_date), MONTH(activity_date)

In this case, the YEAR and MONTH functions are probably what you are looking for. that is if you want different aggregated data for each distinct month (just using MONTH without year would group date by month across years). So something like this:

SELECT YEAR(activity_date) as `year`, MONTH(activity_date) as `month`, [other fields with aggregation functions]
FROM table
GROUP BY `year`, `month`
ORDER BY `year`, `month`

您可以在GROUP BY子句中使用函数,例如MONTH()

GROUP BY YEAR(activity_date), MONTH(activity_date)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM