用于根据两列和不同行计算总和的SQL语法

时间:2015-08-21 12:11:26

标签: sql-server

如何获取在其他列和当前列的前一行计算的字段值。

预期结果如下:

Row No, Year, Week, Count, Sum
1,      2015,    1,    10, 10
2,      2015,    2,     5, 15
3,      2015,    3,     3, 18
4,      2015,    4,     1, 19
.          .     .      .  .
.          .     .      .  .
.          .     .      .  .
52,     2015,   52,     n, n

列[行号],[年份],[周]和[计数]是静态的,我想按下式计算[和]

SUM(Row 1) = Count(Row1)
SUM(Row 2) = Count(Row2) + SUM(Row 1)
SUM(Row 3) = Count(Row3) + SUM(Row 2)
SUM(Row 52) = Count(Row52-1) + SUM(Row52-1)

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

在sqlserver 2012中,您可以使用running sum

SELECT 
  SUM([Count]) over (order by year, week) [Sum]
FROM yourtable

答案 1 :(得分:0)

您可以使用子查询来完成。

Select table.[Row No],Year,Week,Count,Count + IsnUll(t1.Count,0)
from Table
LEFT OUTER JOIN (Select Count,[Row No]-1 as [Row No] from Table) ON Table.[Row No]=t1.[Row No]