Click here to Skip to main content
15,895,656 members
Articles / Database Development / SQL Server

Query for running total in SQL Server

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
24 Aug 2011CPOL 11.6K   1  
Using window functions (partition by) will speed up the process:SELECT Val, SUM(Val) OVER (Partition BY [YourPartitionValue] Order BY [OrderColumn] as CumulativeSumFROM [Table]

Alternatives

Members may post updates or alternatives to this current article in order to show different approaches or add new features.

Please Sign up or sign in to vote.
25 Aug 2011iamalik
I guess this is more faster:SELECT T1.Field1, SUM(T2.Field1) FROM [Table] T1, [Table] T2WHERE T1.Field1 >= T2.Field1GROUP BY T1.Field1
Please Sign up or sign in to vote.
31 Aug 2011Mukit, Ataul 4 alternatives  
Calculate running total or cumulative sum from a table in a SQL Server database.
Please Sign up or sign in to vote.
26 Aug 2011S Douglas
Another way of getting totals, whether it be by group or set is to use the CUBE and ROLLUP predicates.By group (each grouping of FIELD_DESCRIPTION will have a total sum):SELECT FIELD_DESCRIPTION , SUM(FIELD_VALUE)FROM tbl_DataGROUP BY FIELD_DESCRIPTIONWITH CUBEOr:By Cube...
Please Sign up or sign in to vote.
4 Sep 2011fordc03
This will work on SQL 2000/2005/2008.Most cumulative aggregations have constraints such as a begin and end date or grouped by customers.Your solution is good for a single aggregation without much filtering. People will find that the query plans generated would be very similiar to that of...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) The Code Project
United States United States
Elina joined the Code Project team as a software developer in order to make the site run even smoother than it is now. She will also take care of making wishes and promises on the site improvements come to the light sooner than later. When not at work, she enjoys being with her family and wishes there will be at least 30 hours in a day Smile | :)

Comments and Discussions