How do I generate a series of hourly averages in MySQL?

前端 未结 3 1120
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 10:23

I\'ve got data in ten minutes intervals in my table:

2009-01-26 00:00:00      12
2009-01-26 00:10:00      1.1
2009-01-26 00:20:00      11
2009-01-26 00:30:00         


        
3条回答
  •  长情又很酷
    2020-12-15 11:02

    There is also another possibility considering the fact that dates have a string representation in the database:

    You can use SUBSTRING(thetime, 1, [len]), extracting the common part of your group. For the example with hourly averages you have the SQL query

    SELECT SUBSTRING(thetime, 1, 13) AS hours, AVG(value) FROM hourly_averages GROUP BY hours
    

    By the len parameter you can specify the aggregated time interval considering the MySQL date format yyyy-MM-dd HH:mm:ss[.SS...]:

    • len = 4: group by years
    • len = 7: group by months
    • len = 10: group by days
    • len = 13: group by hours
    • len = 16: group by minutes
    • len = 19: group by seconds

    We encountered a better performance of this method over using date and time function, especially when used in JOINs in MySQL 5.7. However in MySQL 8 at least for grouping both ways seem to take approximately the same time.

提交回复
热议问题