0

我有几个 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?

4

2 回答 2

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
于 2012-06-13T15:10:05.313 回答
4

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

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

于 2012-06-13T15:36:35.473 回答