I have MySQL DB with accumulated data from sensors, and I want to calculate maximum value for a sensor within intervals.
Here is data fragment:
"id", "dateCreate", "temp"
"2", "2017-08-19 03:19:08", "24.63"
"3", "2017-08-19 03:24:11", "24.65"
"14", "2017-08-19 03:29:15", "24.63"
"15", "2017-08-19 03:38:49", "24.63"
"26", "2017-08-19 03:43:53", "24.56"
"37", "2017-08-19 03:48:55", "24.60"
"38", "2017-08-19 03:53:59", "24.65"
"49", "2017-08-19 03:59:01", "24.70"
"50", "2017-08-19 04:04:04", "24.75"
"51", "2017-08-19 04:09:07", "24.70"
"62", "2017-08-19 04:14:07", "24.70"
I want to group such data into chunks of N
(size may be different) rows and run MAX
(or MIN
) over each chunk.
The expected result if I group the sample data into 3 rows would be:
"id", "dateCreate", "temp"
"3", "2017-08-19 03:24:11", "24.65"
"15", "2017-08-19 03:38:49", "24.63"
"50", "2017-08-19 04:04:04", "24.75"
"51", "2017-08-19 04:09:07", "24.70"
I spend several hours searching for the solution and unfortunately wasn't able to find any working approach.
I imagine the solution may be based on a technique with row numbering and/or limiting rows (with offsetting) within sub-queries, but test queries I managed to create looked awful and didn't work as expected (moreover they were too slow).
Here is an example which gets maximum value within one interval:
SELECT a.*
FROM (
SELECT *
FROM MultiTemp
ORDER BY dateCreate DESC
LIMIT 100 -- OFFSET is needed
) AS a
INNER JOIN (
SELECT MAX(temp) AS temp
FROM (
SELECT *
FROM MultiTemp
ORDER BY dateCreate DESC
LIMIT 100 -- OFFSET is needed
) AS L
) AS M
ON a.temp = M.temp
Further data processing is done with PHP (to generate graphs), so the above mentioned generic query my be equipped with OFFSET
for other intervals. Unfortunately it is too slow...
So far the question is mainly focused on grouping: selecting other data fields may be implemented with approaches like proposed here.
I believe such task (group into chunks of fixed size) is much easier for the engine than grouping by some column, so I probably overlooked something...
Update 1: the column id
contains auto-incremented value, but there is no guarantee it is continuous - the table holds data from different devices, and I want to group for one device (I had left this aspect out of scope for brevity). I've adjusted the sample data. Sorry for confusion!