@myvar:=0;
@rownum:=0;
SELECT result.readdate,
AVG(total_gallons) AS total_gallons
FROM (SELECT middle_rows.readdate,
numerated_rows.rownum,
numerated_rows.total_gallons
FROM (SELECT IF(@myvar = readdate, @rownum := @rownum + 1, @rownum := 0) AS rownum,
@myvar := readdate AS readdate_alias,
total_gallons
FROM _temp_total_gallons
ORDER BY readdate,
total_gallons) numerated_rows,
(SELECT readdate,
COUNT(*) / 2 median
FROM _temp_total_gallons
GROUP BY readdate) middle_rows
WHERE numerated_rows.rownum BETWEEN ( middle_rows.median - IF(median = ROUND(median), 1, 0) - 0.5 ) AND ( middle_rows.median - IF(median = ROUND(median), 0, 0.5) )
AND numerated_rows.readdate_alias = middle_rows.readdate) result
GROUP BY readdate
如您所见,它使用@myvar
和@rownum
作为会话变量SELECT IF(@myvar = readdate, @rownum := @rownum + 1, @rownum := 0)
问题是无法在存储过程中运行此问题,因为@myvar:=0
语法未知,我必须引用/设置内部选择运行时。
您如何重写上述查询以在存储过程中使用?
要测试的样本数据和查询可以在https://gist.github.com/948250发现 要测试的第二组数据是https://gist.github.com/25b991396d0dd6968b7e
答案 0 :(得分:1)
使用
SET @myvar := 0;
在SP内部分配值:
DELIMITER $$
CREATE PROCEDURE prc_median()
BEGIN
SET @myvar:=0;
SET @rownum:=0;
SELECT result.readdate,
AVG(total_gallons) AS total_gallons
FROM (SELECT middle_rows.readdate,
numerated_rows.rownum,
numerated_rows.total_gallons
FROM (SELECT IF(@myvar = readdate, @rownum := @rownum + 1, @rownum := 0) AS rownum,
@myvar := readdate AS readdate_alias,
total_gallons
FROM _temp_total_gallons
ORDER BY readdate,
total_gallons) numerated_rows,
(SELECT readdate,
COUNT(*) / 2 median
FROM _temp_total_gallons
GROUP BY readdate) middle_rows
WHERE numerated_rows.rownum BETWEEN ( middle_rows.median - IF(median = ROUND(median), 1, 0) - 0.5 ) AND ( middle_rows.median - IF(median = ROUND(median), 0, 0.5) )
AND numerated_rows.readdate_alias = middle_rows.readdate) result
GROUP BY readdate;
END;
$$