Question

I would like to use highcharts to see the temperature behaviour on last hour.

I record 20 to 30 temperature values for each hour. Here, I would like to extract, for last hour, 4 to 6 average values (one value for a 10 or 15 minutes period) and plot them. Maybe I will change that to 3 values (one for 20 minutes) to get something smoother.

I have values like that (for example) :

mysql> SELECT date,valeur FROM temperature
+---------------------+--------+
| date                | valeur |
+---------------------+--------+
| 2013-09-26 11:30:40 |   25.2 |
| 2013-09-26 11:33:19 |   25.4 |
| 2013-09-26 11:34:12 |   25.5 |
| 2013-09-26 11:38:37 |   25.4 |
| 2013-09-26 11:39:30 |   25.4 |
| 2013-09-26 11:40:23 |   25.4 |
| 2013-09-26 11:43:02 |   25.4 |
| 2013-09-26 11:45:41 |   25.3 |
| 2013-09-26 11:47:33 |   25.3 |
| 2013-09-26 11:51:07 |   25.4 |
| 2013-09-26 11:51:52 |   25.3 |
...

I tried to extract with this command :

SELECT ROUND(UNIX_TIMESTAMP(date)/(15 * 60)) AS timekey, ROUND(AVG(valeur),1) AS a FROM temperature WHERE date >= (now() - INTERVAL 1 HOUR) GROUP BY timekey ORDER BY DATE;

But I don't get any output. If I change the interval to 5 hours, I get 16 values :

[1534861, 24.600000]
[1534862, 24.600000]
[1534863, 24.600000]
[1534864, 24.700000]
[1534865, 24.700000]
[1534866, 24.600000]
[1534867, 24.600000]
[1534868, 24.600000]
[1534869, 24.600000]
[1534870, 24.600000]
[1534871, 24.700000]
[1534872, 24.700000]
[1534873, 24.700000]
[1534874, 24.800000]
[1534875, 25.000000]
[1534876, 25.200000]

Any idea how to correct this mysql request ?

Thanks you all

Greg

edit - See selected answer : the code was good, but the timezone wasn't !

Was it helpful?

Solution

I am guessing your issue is most likely a timezone difference of 1 hour.

if you get no values for last hour but you get 16 for last 5(making up 4 hours worth of values), that sounds like you have no values for last hour. If you are certain you do, check the timezone of data vs timezone of now()

try using sysdate perhaps. Quote from manual:

In addition, the SET TIMESTAMP statement affects the value returned by NOW() but not by SYSDATE(). This means that timestamp settings in the binary log have no effect on invocations of SYSDATE(). Setting the timestamp to a nonzero value causes each subsequent invocation of NOW() to return that value. Setting the timestamp to zero cancels this effect so that NOW() once again returns the current date and time.

See the description for SYSDATE() for additional information about the differences between the two functions.

OTHER TIPS

This should work (note floor() usage):

SELECT from_unixtime(floor(unix_timestamp(date) / 15 * 60) * 15 * 60) AS tstamp,
    round(avg(valeur),1) AS a
FROM temperature
WHERE date >= (now() - INTERVAL 1 HOUR)
GROUP BY 1
ORDER BY 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top