SQL 2008 运行 分组平均值

SQL 2008 Running average with group by

所以我有一个 table 包含下面的列。 我想从 positiondate 计算一个 运行 平均值,例如 3 天前,在 dealno 上分组。 我知道如何处理 "case by" 但问题是我有大约 200 个不同的 DealNo 所以我不想为每笔交易写一个自己的 case by 条款。

在 dealNo 1 上,它期望的输出应该是平均(149 243 440 + 149 224 446 + 149 243 451)

DealNo      PositionDate    MarketValue
    1   |   2016-11-27  |   149 243 440
    2   |   2016-11-27  |   21 496 418
    3   |   2016-11-27  |   32 249 600
    1   |   2016-11-26  |   149 243 446
    2   |   2016-11-26  |   21 496 418
    3   |   2016-11-26  |   32 249 600
    1   |   2016-11-25  |   149 243 451
    3   |   2016-11-25  |   32 249 600
    2   |   2016-11-25  |   21 496 418
    3   |   2016-11-24  |   32 249 600
    1   |   2016-11-24  |   149 225 582
    2   |   2016-11-24  |   21 498 120
    1   |   2016-11-23  |   149 256 867
    2   |   2016-11-23  |   21 504 181
    3   |   2016-11-23  |   32 253 440
    1   |   2016-11-22  |   149 256 873
    2   |   2016-11-22  |   21 506 840
    3   |   2016-11-22  |   32 253 440
    1   |   2016-11-21  |   149 234 535
    2   |   2016-11-21  |   21 509 179
    3   |   2016-11-21  |   32 253 600

我尝试了下面的脚本,但它不是很有效,因为我的 table 包含大约 300k 行和大约 200 个不同的 dealno。 在 SQL 2008 年有更有效的方法吗?

with cte as (

SELECT ROW_NUMBER() over(order by dealno, positiondate desc) as Rownr,
        dealno,
        positiondate,
        Currency,
        MvCleanCcy
  FROM T1
           )

select 
rownr, positiondate, DealNo, Currency,
mvcleanavg30d = (select avg(MvCleanCcy) from cte2 where Rownr between c.Rownr and c.Rownr+3)

 from cte as c

您不需要 window 函数。您可以使用 outer apply:

select t1.*, tt1.marketvalue_3day
from t1 outer apply
     (select avg(tt1.marketvalue) as marketvalue_3day
      from (select top 3 tt1.*
            from t1 tt1
            where tt1.deal1 = t1.deal1 and
                  tt1.positiondate <= t1.positiondate
            order by tt1.positiondate desc
           ) tt1
     ) tt1;