本文介绍了MS Sql 服务器中的累计总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
I need to get the cumulative (running) total of a column in ms-sql server. I.e. if there is a column named "Marks", then corresponding to each row cumulative sum will the sum of current and previous rows. Can we attain the result without using joins? Because my query is pretty big.
I have included a sample table and data:
CREATE TABLE "SCORE_CHART"
(
"STUDENT_NAME" NVARCHAR(20),
"MARKS" INT
)
INSERT INTO SCORE_CHART (STUDENT_NAME, MARKS) VALUES ('STUD1', 95);
INSERT INTO SCORE_CHART (STUDENT_NAME, MARKS) VALUES ('STUD2', 90);
INSERT INTO SCORE_CHART (STUDENT_NAME, MARKS) VALUES ('STUD3', 98);
SELECT STUDENT_NAME, MARKS FROM SCORE_CHART;
Expected result:
In oracle it’s easy to write like:
SELECT
STUDENT_NAME,
MARKS,
SUM(MARKS) OVER (ORDER BY STUDENT_NAME) CUM_SUM
FROM SCORE_CHART
ORDER BY STUDENT_NAME;
Thanks in advance.
解决方案
The same query is supported from 2012 onwards. In older versions there are several approaches. Refer this http://www.sqlperformance.com/2012/07/t-sql-queries/running-totals
这篇关于MS Sql 服务器中的累计总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!