选择有限的平均值

时间:2012-06-13 15:05:00

标签: mysql average

我有几个SQL语句来计算存储过程中的平均值:

SELECT AVG(x) INTO _5dayaverage FROM (SELECT x FROM my_data ORDER BY create_date DESC LIMIT 5) AS temptable;
SELECT AVG(x) INTO _10dayaverage FROM (SELECT x FROM my_data ORDER BY create_date DESC LIMIT 10) AS temptable;

是否有可能以这样的方式编写这些内容,即我只进行一次SELECT而不是使用派生表?由于我需要计算5天,10天,20天,28天,30天,35天和50天的平均值,因此可以在一个查询中完成所有操作而不是一遍又一遍地执行SELECT吗?

2 个答案:

答案 0 :(得分:4)

您可以将ROW_NUMBER()与公用表表达式一起使用。假设您正在使用SQL Server 2005 +

WITH Numbered AS (
SELECT ROW_NUMBER() OVER(ORDER BY create_date DESC) AS RowNum,
   X
FROM my_data)

SELECT AVG(CASE WHEN RowNum <= 5 THEN X ELSE NULL END) AS _5_Day_Avg,
   AVG(CASE WHEN RowNum <= 10 THEN X ELSE NULL END) AS _10_Day_Avg
FROM Numbered

答案 1 :(得分:4)

您需要使用递增变量来获取MySQL中的row_number:

SELECT  AVG(CASE WHEN RowNumber <= 5 THEN X END) AS Avg_5,
        AVG(CASE WHEN RowNumber <= 10 THEN X END) AS Avg_10,
        AVG(CASE WHEN RowNumber <= 15 THEN X END) AS Avg_15,
        AVG(CASE WHEN RowNumber <= 20 THEN X END) AS Avg_20,
        AVG(CASE WHEN RowNumber <= 25 THEN X END) AS Avg_25,
        AVG(CASE WHEN RowNumber <= 30 THEN X END) AS Avg_30,
        AVG(CASE WHEN RowNumber <= 35 THEN X END) AS Avg_35
FROM    (   SELECT  @i:= @i + 1 AS RowNumber, x
            FROM    My_Data,
                    (SELECT @i:=0) AS i
            ORDER BY Create_Date DESC
        ) AS Data

http://sqlfiddle.com/#!2/7a250/1