Possible Duplicate:
Calculate a Running Total in SqlServer
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.
You said no joins, what about a apply? ;)
With a index on student_name speed should be okay!
Use Recursive CTE to achive this.
try this:
you can get the cumulative sum just by joining the same table itself
SQL Fiddle demo
JUSt doing a join doesn't seem to guarantee order but comes up with the final answer ok:
just seem the NO JOINS rule - will re-think
EDIT - running ok now: LIVE FIDDLE HERE
Creating the data
Using a recursive CTE:
As mentioned in a comment to you OP there is a similar question HERE ON SO In that question Sam Saffron put forward a very elegant way of doing a running total using
UPDATE
. This is is applied to your data:Using the same data created above but with the UPDATE trick:
Check the query for Recursive CTE.
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