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


2 comments:

  1. 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

    ReplyDelete
  2. 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 :)

    ReplyDelete