每个前一行添加值

时间:2015-03-04 01:47:24

标签: sql sql-server sql-server-2012

我有一张表Grader

+--------------------------+
|GraderName | Graded_Items |
+--------------------------+
|    A      |       21     |
|    B      |        7     |
|    C      |       17     |
|    D      |       91     |
|    E      |       84     |
|    F      |       52     |
|    G      |       34     |
+--------------------------+

我希望将第一行和第二行的SUM放在第二行;第一,第二和第三行的SUM放在第三行;等等到其他行。见下文:

+--------------------------------+
|GraderName | Graded_Items       |
+--------------------------------+
|    A      |21                  |
|    B      |21+7                |
|    C      |21+7+17             |
|    D      |21+7+17+91          |
|    E      |21+7+17+91+84       |
|    F      |21+7+17+91+84+52    |
|    G      |21+7+17+91+84+52+34 |
+--------------------------------+

我想达到这个结果:

+--------------------------+
|GraderName | Graded_Items |
+--------------------------+
|    A      |       21     |
|    B      |       28     |
|    C      |       45     |
|    D      |      136     |
|    E      |      220     |
|    F      |      272     |
|    G      |      306     |
+--------------------------+

我已尝试过此查询:

SELECT Grader,Graded_Items FROM Grader WHERE Grader='A'
UNION ALL
SELECT MAX(Grader),SUM(Graded_Items) FROM Grader WHERE Grader in ('A','B')
UNION ALL
SELECT MAX(Grader),SUM(Graded_Items) FROM Grader WHERE Grader in ('A','B','C')
UNION ALL
SELECT MAX(Grader),SUM(Graded_Items) FROM Grader WHERE Grader in ('A','B','C','D')
UNION ALL
SELECT MAX(Grader),SUM(Graded_Items) FROM Grader WHERE Grader in ('A','B','C','D','E')
UNION ALL
SELECT MAX(Grader),SUM(Graded_Items) FROM Grader WHERE Grader in ('A','B','C','D','E','F')

但是,我的问题是表格一直在变化,例如GraderName正在填充其对应的Graded_Items。有没有其他方法可以达到我的预期效果?

非常感谢您的帮助。谢谢。

1 个答案:

答案 0 :(得分:3)

使用Sum over()技巧获取正在运行的总数

select GraderName, 
       sum(Graded_Items) over(order by GraderName) As Graded_Items
From yourtable