I’ve got a database consisting of the following Columns:
time | windSpeed | temperature | more parameters
Every 30 seconds a row is automatically added with the current wind speed, temperature etc.
To be able to display a graph I would like to construct a MySQL Query which displays the average per hour for 24 hours starting from the newest entry.
So the new relation/table should look like this:
hour | avgWindspeed | avgTemperature
-1 | 13.3 | -5.8
-2 | 16.4 | -3.1
This is how far I got:
Each row should me made up of 60minutes / 30 seconds = 120 rows.
SELECT *
FROM (
SELECT @row := @row +1 AS rownum, tijd, wind_s, luchtdruk, temp
FROM (
SELECT @row :=0
)r, weer_actueel
ORDER BY tijd DESC
)ranked
WHERE rownum %120 =1
It now displays the 120th row instead of displaying the average of the 120 rows.
Could anyone help me?
Edit 1:
- the programming language I used is PHP; but I would love a native MySQL solution.
- the column ‘time’ is a mysql datetime value
By grouping by “Per Hour”, you get all hours broken down. The WHERE clause always goes explicitly 24 hours from whatever is the current date/time, so this will even account for a time of 14:37 in the afternoon to one day prior 14:37.
Then, by using the min( w.time ), we are getting the first actual full date/time stamp for the order by so we can sort it by most recent time at the top going backwards as what would be the correct order if the time is 7 in the morning and you are going backwards to hour 23 of the prior day, down to hour 8. This makes sure its by proper time.
If you want the breaking to exactly be based on the minute within the hour break… such as
that will take a bit more finesse by pre-querying to detect that starting point which will result in a large case construct of 24 hours, but we can even build that out with @sql variables… Try this..
The inner query with the sql vars primes the MyHour with 0 and CurTime with now() (date and time). Then does a Cartesian (no join) to the weer_actueel table with a limit of 24 records. When building out the results of this HourlyGaps inner query, the @Vars keep going backwards one hour at a time… The @CurTime starts as the end, then subtracts one hour from itself to become the beginning hour for that time slot… which then becomes the ending time for the next prior hour…. completes for a cycle of 24 hours.
This is then re-joined to the stats table only for those times within the given matched time slots of 24 hours. Since we have the “@MyHour” being saved as HoursAgo, and that keeps increasing for each row, we also have that for the basis of proper sorted output.