MySQL: select query, 5 minute increment

一曲冷凌霜 提交于 2019-12-22 10:08:22

问题


I have a weather database which gets datasets about every 70 seconds (depends on when the weather-station delivers the data).
I want to graph it using Pchart but i have too many samples so the X axis is screwed up.
So i want the data for about every 5 minutes. (or every 30 minutes)
The query i currently have is this:

SELECT time, temp_out FROM wmr200 WHERE date(time) = curdate()

This gets the samples for the last 24 hours but there are too many.


回答1:


The following will get you a sample consisting of any data with a timestamp at :00, :05, :10 ...

SELECT time, temp_out FROM wmr200 WHERE date(time) = curdate()
    AND mod(minute(time),5) = 0

I'm using the modulo function to check if the minute part of the time is (0 or) divisible by 5.


If you need only one result for each time segment, we've got to get quite a bit more complex.

SELECT concat(date(time),' ',hour(time),':',round(minute(time)/5,0)*5), 
       min(temp_out), avg(temp_out), max(temp_out) 
FROM wmr200 
GROUP BY date(time), hour(time), round(minute(time)/5,0)*5

I don't have access to a MySQL instance to test it out right now, but here's the idea. It groups by every five minutes, by grouping by date, hour, and round(minute(time)/5,0)*5 - which rounds minute to the nearest 5.

It selects the value of time that it should be grouped around, and the min, avg, and max temp_out, as I wasn't sure which of these would best apply to your situation.

If, however, your DB doesn't have data for a five minute stretch (or 30 minute stretch, if that's what you're using), it still may not have data for a sample point.




回答2:


In case anyone else happens upon this page, here's a solution that's comparable to Sam's. It makes use of Unix timestamps and integer division to "bin" and average values over any arbitrary time period.

SELECT FROM_UNIXTIME((UNIX_TIMESTAMP(time) div (5*60))*(5*60)+(5*60)) as timeIntervals,
round(avg(temp_out),3) as temp_out
FROM wmr200 
GROUP BY 1


来源:https://stackoverflow.com/questions/10403039/mysql-select-query-5-minute-increment

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