开发者

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

开发者 https://www.devze.com 2023-03-15 04:02 出处:网络
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).

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 s开发者_开发技巧imply 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?


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.


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消