本文介绍了当前行的值+前几行的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从中转换表中的列:
How would you do to transform a Column in a table from this:
ColumnA ColumnB
2 a
3 b
4 c
5 d
1 a
对此:
ColumnA ColumnB
3 a
6(=3+3) b
10(=4+3+3) c
15(=5+4+3+3) d
我有兴趣见到esp.您会选择哪种方法.
I'm interested to see esp. what method you would pick.
推荐答案
像这样:
;WITH cte
AS
(
SELECT ColumnB, SUM(ColumnA) asum
FROM @t
gROUP BY ColumnB
), cteRanked AS
(
SELECT asum, ColumnB, ROW_NUMBER() OVER(ORDER BY ColumnB) rownum
FROM cte
)
SELECT (SELECT SUM(asum) FROM cteRanked c2 WHERE c2.rownum <= c1.rownum),
ColumnB
FROM cteRanked c1;
这应该给您:
ColumnA ColumnB
3 a
6 b
10 c
15 d
这篇关于当前行的值+前几行的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!