i have a table like this
from | to | value
-----------------------
08:10 | 08:12 | 2
08:13 | 08:20 | 5
08:30 | 08:45 | 3
08:46 | 08:55 | 1
and i need to group by intervals of say 1, 10, 60 minutes and get the average value, assuming each minute has one value.
Note: there are holes between the ranges and from is inclusive, to non inclusive
from | to | average_value
-----------------------
08:10 | 08:19 | 4
08:20 | 08:29 | 5
08:30 | 08:39 | 3
08:40 | 08:49 | 2
08:50 | 08:59 | 1
My idea was to use a stored procedure to transform the entries to
time | value
-----------------------
08:10 | 2
08:11 | 2
08:12 | 2
08:13 | 5
...
08:20 | 5
08:30 | 3
...
08:45 | 3
08:50 | 1
...
08:55 | 1
my first attempt
DELIMITER $$
CREATE PROCEDURE Decompose()
BEGIN
DECLARE num_rows INT;
DECLARE from DateTime;
DECLARE to DateTime;
DECLARE value double;
DECLARE friends_cur CURSOR FOR SELECT from, to, value FROM sourcetable;
-- 'open' the cursor and capture the number of rows returned
-- (the 'select' gets invoked when the cursor is 'opened')
OPEN friends_cur;
select FOUND_ROWS() into num_rows;
WHILE num_rows > 0 DO
FETCH friends_cur INTO from, to, value;
SELECT from, value;
SET num_rows = num_rows - 1;
END WHILE;
CLOSE friends_cur;
END$$
DELIMITER ;
leads to 'Command out of sync' error because each SELECT in the loop will create a new resultset everytime instead of returning a row.
Questions:
- can i make the stored procedure work somehow?
- is there a sql possible to get the average value for each interval?