[英]stored procedure returning a calculated resultset
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. 我需要按照例如1分钟,10分钟,60分钟的间隔进行分组,并获得平均值,假设每一分钟都有一个值。
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. 导致“命令不同步”错误,因为循环中的每个SELECT每次都会创建一个新的结果集,而不是返回一行。
Questions: 问题:
I think your fundamental plan is sound. 我认为您的基本计划是正确的。
I would start by creating a numbers table. 我将从创建一个数字表开始。 ( Creating a "Numbers Table" in mysql ) ( 在mysql中创建“数字表” )
From that, convert that into a table with rows for each minute of the day for which you wish to calculate the average values - including those that don't have any value - and a column to indicate which interval that particular minute belongs to 然后,将其转换为一个表格,其中包含您要计算平均值的一天中的每一分钟的行(包括没有任何值的行)和一列,以指示该特定分钟所属的间隔
Time Interval
08:00 1
08:01 1
08:02 1
08:03 1
08:04 1
08:05 2
08:06 2
....
And from that left join to your sample table using 并从左边开始使用
ON intervals.Time >= Samples.Time and intervals.Time<Sample.Time
to produce a query of the intervals, then do the average against that. 生成间隔查询,然后对间隔进行平均。
I don't think you need the cursor. 我认为您不需要光标。
(I would give more concrete examples, but I lack knowledge of some of MySql variety of SQL intricacies) (我会给出更具体的示例,但我缺乏MySql各种SQL复杂性的知识)
may be you can try something like this in a single query: 也许您可以在单个查询中尝试类似的操作:
SELECT DATE_FORMAT(TIMEDIFF('08:12','08:10'), '%m') AS time, AVG(value) avg_value
FROM table_name
GROUP BY 1
ORDER BY avg_value DESC;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.