组成4排超过一圈

时间:2017-06-02 03:37:43

标签: tsql

对于模糊的标题感到抱歉,但我不确定如何说出问题。我想要做的是如果每4条记录分组一列,但分组将重叠

 Game       Strikeouts
    1.                 25
    2.                 10
    3.                 10
    4.                 11
    5.                 16

显示第一组将是1-4游戏,总和将是56,第二组将是2-5而sun将是47,依此类推到最后一条记录。

2 个答案:

答案 0 :(得分:4)

另一个选择

Select Game
      ,Strikeouts = sum(Strikeouts) over (Order By Game ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING ) 
 From  YourTable
 Order By Game

返回

Game    Strikeouts
1       56
2       47
3       37
4       27
5       16

答案 1 :(得分:3)

我只是将接下来的3行的值添加到实际行中:

CREATE TABLE #TEST (
  Game int
 ,Strikeouts int
)
INSERT INTO #TEST VALUES 
(1,25),(2,10),(3,10),(4,11),(5,16)

-- act. row + 3 following rows
SELECT Game, Strikeouts + LEAD(Strikeouts,1,0) OVER (ORDER BY Game) + LEAD(Strikeouts,2,0) OVER (ORDER BY Game) + LEAD(Strikeouts,3,0) OVER (ORDER BY Game) as Strikeouts
FROM #TEST

输出:

Game |Strikeouts
-----+-----------
  1  |        56
  2  |        47
  3  |        37
  4  |        27
  5  |        16

随着SQL Server 2012引入了滞后