Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: select query, 5 minute increment

Tags:

sql

mysql

pchart

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.

like image 911
HyperDevil Avatar asked Dec 17 '22 00:12

HyperDevil


1 Answers

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.

like image 193
Sam DeHaan Avatar answered Dec 29 '22 00:12

Sam DeHaan