3列滚动平均3个月

时间:2016-06-29 17:46:59

标签: tsql sql-server-2012

需要帮助

输入

Date        A           B       C
2015-10-31  1.49        3.7     7.8
2015-11-30  1.45        3.6     7.6
2015-12-31  1.41        3.7     8.0
2016-01-31  1.33        3.7     8.3
2016-02-29  1.29        4.1     8.6
2016-03-31  1.46        4.4     9.7

CREATE TABLE dbo.ThreeMonth(RDate DATE,A FLOAT,b FLOAT,C FLOAT)

插入dbo.threemonth (RDate,a,b,c)  价值观('2015-10-31',1.49,3.7,7.8) 插入dbo.threemonth (RDate,a,b,c)  价值观('2015-11-30',1.45,3.6,7.6)

插入dbo.threemonth (RDate,a,b,c)  价值观('2015-12-31',1.41,3.7,8.0)

插入dbo.threemonth (RDate,a,b,c)  价值观('2016-01-31',1.33,3.7,8.3)

插入dbo.threemonth (RDate,a,b,c)  价值观('2016-02-29',1.9,4.1,8.6)

插入dbo.threemonth (RDate,a,b,c)  价值观('2016-03-31',1.46,4.4,9.7)

插入dbo.threemonth (RDate,a,b,c)  价值观('2016-04-30',1.35,4.3,9.4)

SELECT * FROM threemonth

- 尝试了以下查询

选择rdate,avg(A)
    超过(         按路线订购         2前进和当前行之间的行     ) 从三个月开始

输出

我需要显示滚动3个月的平均值3个字符串a,b,c .WHEN我添加AVG(b)和AVG(c)它给出错误

“列'threemonth.RDate'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。”

- 我也想要OUTPUT IN格式

 2015-10-31 NULL -- Because 3 months are not available avg cannot be calculated
2015-11-30  NULL -- Because 3 months are not available avg cannot be calculated
2015-12-31  1.45 
2016-01-31  1.39666666666667
2016-02-29  1.54666666666667
2016-03-31  1.56333333333333
2016-04-30  1.57 code here

有人可以建议解决上述问题吗?我需要将AVG用于更多1列,并在上面显示的格式中显示输出所有3列?

1 个答案:

答案 0 :(得分:0)

像这样的东西

;with cteBase as (SELECT *,RowNr = Row_Number() Over (Order by RDate) FROM threemonth )
  Select RDate,Avg=(select Avg(A) from cteBase where RowNr between A.RowNr-2 and A.RowNr and A.RowNr>2)
     From cteBase A

返回

RDate       Avg
2015-10-31  NULL
2015-11-30  NULL
2015-12-31  1.45
2016-01-31  1.39666666666667
2016-02-29  1.54666666666667
2016-03-31  1.56333333333333
2016-04-30  1.57

对于Cols A,B和C

 ;with cteBase as (SELECT *,RowNr = Row_Number() Over (Order by RDate) FROM threemonth )
  Select RDate
        ,AvgA=(select Avg(A) from cteBase where RowNr between A.RowNr-2 and A.RowNr and A.RowNr>2)
        ,AvgB=(select Avg(B) from cteBase where RowNr between A.RowNr-2 and A.RowNr and A.RowNr>2)
        ,AvgC=(select Avg(C) from cteBase where RowNr between A.RowNr-2 and A.RowNr and A.RowNr>2)
     From cteBase A