Add a Total of All Columns in a Table using SQL Server 2005/2008

Here's a scenario where you have a table with numeric columns. While displaying all the rows, you also want to display the total of each column at the end. How do you do summarize the data? Use WITH ROLLUP

SAMPLE DATA


DECLARE @Numbers TABLE


(


    ID varchar(10), Marks1 smallint, Marks2 smallint, Marks3 smallint, Marks4 smallint


)


 


INSERT @Numbers


SELECT 'S1', 6, 3, 6, 8 UNION ALL


SELECT 'S2', 4, 8, 1, 9 UNION ALL


SELECT 'S3', 2, 6, 3, 5 UNION ALL


SELECT 'S4', 5, 8, 2, 9 UNION ALL


SELECT 'S5', 5, 5, 3, 5




QUERY


SELECT SUM(Marks1) M1, SUM(Marks2) M2, SUM(Marks3) M3, SUM(Marks4) M4


FROM @Numbers


GROUP BY ID


WITH ROLLUP




RESULT


M1    M2    M3    M4


6    3    6    8


4    8    1    9


2    6    3    5


5    8    2    9


5    5    3    5


22   30   15  36



About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

2 comments:

Unknown said...

Actually this should be done by a Reporting tool. If you do it via sql,it would take lot of time for execution. Test your code with large number of data

Madhivanan

Suprotim Agarwal said...

Madhivanan,

I agree to most of your comments. However these topics I have written on, are taken from requirements I face while dealing with my clients, Q&A rounds -- to be considered more of instant 'quick-to-do' solutions.

Keep dropping in your comments and alternative ways of achieving these requirements as not everyone would be looking out to take a quick bite of code :)