Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

Query for running total in SQL Server

2.00/5 (1 vote)
26 Aug 2011CPOL 9.9K  
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...

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):


SQL
SELECT
	FIELD_DESCRIPTION
	, SUM(FIELD_VALUE)
FROM
	tbl_Data
GROUP BY
	FIELD_DESCRIPTION
WITH CUBE

Or:


By Cube (the final set of FIELD_VALUE will have a total sum):


SQL
SELECT
	FIELD_DESCRIPTION
	, SUM(FIELD_VALUE)
FROM
	tbl_Data
GROUP BY
	FIELD_DESCRIPTION
WITH ROLLUP

Reference:
Summarizing Data Using ROLLUP[^].

License

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