SQL query to obtain an Average value for set periods of time

房东的猫 提交于 2019-12-06 05:59:10

问题


I have a MySQL database which is used to store power readings, with a reading added once per minute. (i.e. 1,440 readings per day).

time      power
----      -----
00:00:00    346
00:01:00    352
00:02:00    247

Using PHP I want to produce a graph from this data, but I don't want 1,440 points on the graph. I might choose to split it into 15 minute chunks (which will give me 96 points). Also, I don't want to simply take every fifteenth value, as this will give misleading results. What I want to do is use an SQL query that returns the data in 15 minutes blocks and gives the power reading as an average.

The output might look something like this:

starttime   avgpower
---------   --------
00:00:00         342
00:15:00         490
00:30:00         533

Is there an SQL function that will do this for me? or am I going to have to perform this calculation in my PHP code?


回答1:


Here is your query:

SELECT STR_TO_DATE(CONCAT(DATE_FORMAT(`time`, '%H'), ':', (FLOOR(DATE_FORMAT(`time`, '%i') / 15) * 15), ':00'), '%H:%i:%s') `starttime`, AVG(`power`) `avgpower`
FROM `tablea`
GROUP BY `starttime`;

Please feel free to replace the table (tablea) and columns (time and power) names according to your schema.

Hope this helps.




回答2:


You can probably group by the rounded value of minutes/4 and then select the average of the power reading field. You might prefer using the floor function over rounding the number of minutes.




回答3:


Had the same issue. As Don Kirkby pointed out, I solved it with this code:

SELECT time, AVG(power) AS avgpower,  ROUND(UNIX_TIMESTAMP(time)/(15*60)) AS timekey
FROM table
GROUP BY timekey


来源:https://stackoverflow.com/questions/6457362/sql-query-to-obtain-an-average-value-for-set-periods-of-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!