SQL Server Admin
T-SQL Articles

April 19, 2009

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



Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter



 
  Feedback:

comments

2 Responses to "Add a Total of All Columns in a Table using SQL Server 2005/2008"
  1. Madhivanan said...
    February 3, 2010 11:40 PM

    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

  2. Suprotim Agarwal said...
    February 5, 2010 10:50 AM

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

 

Copyright © 2009-2011 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions