Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server TSQL组和过去3年的平均值_Sql Server_Performance_Tsql - Fatal编程技术网

Sql server TSQL组和过去3年的平均值

Sql server TSQL组和过去3年的平均值,sql-server,performance,tsql,Sql Server,Performance,Tsql,我想使用tsql查找按年份分组的结果及其过去3年的平均金额,精确到小数点后2位 data Year amount 2017 100 2017 200 2016 300 2016 100 2015 200 2015 200 2014 100 2013 100 expected result year amount 2017 183.33 2016 166.66 2015 13

我想使用tsql查找按年份分组的结果及其过去3年的平均金额,精确到小数点后2位

    data

    Year amount
    2017 100
    2017 200
    2016 300
    2016 100
    2015 200
    2015 200
    2014 100
    2013 100

    expected result
    year amount
    2017 183.33
    2016 166.66
    2015 133.33
    2014 100 
    2013 100
使用从子查询中获取过去三年的平均值,该子查询平均该年的金额

select 
    year
  , amount = avg(amount) over (order by year rows 2 preceding)
from (
  select year, amount = avg(convert(decimal(19,2),amount))
  from t
  group by year
  ) as s
order by year desc
rextester演示:

返回:

+------+------------+
| year |   amount   |
+------+------------+
| 2017 | 183.333333 |
| 2016 | 166.666666 |
| 2015 | 133.333333 |
| 2014 | 100.000000 |
| 2013 | 100.000000 |
+------+------------+

你尝试了什么?奇怪的预期结果。你似乎错过了你迄今为止所做的尝试。为什么2015年的价值是133.33?不是应该是200吗?