SQL Server: Calculate Summary and Column Summary

This post shows how to show a summary of similar rows as well as column summary for SQL Server table data. Suppose you want to generate the total of a column and display it at the end of the result set. You can use at least two methods as shown below:

Consider the following data:


declare @t table(name varchar(100), amount decimal(12,2))
insert into @t
select 'test1', 1000 union all
select 'test1', 2000 union all
select 'test1', 3000 union all
select 'test2', 1500 union all
select 'test3', 600 union all
select 'test3', 1800

If you want to want to sum the amount for each name and also show the total of all names
at the end, use any of the following methods


select coalesce(name,'Total') as name, SUM(amount) as amount from @t
group by name
with rollup


select name, SUM(amount) as amount from @t
group by name
union all
select 'Total',SUM(amount) from @t

sql server total subtotal

About The Author

Madhivanan,an MSc computer Science graduate from Chennai-India, works as a works as a Lead Subject Matter Expert at a company that simplifies BIG data. He started his career as a developer working with Visual Basic 6.0, SQL Server 2000 and Crystal Report 8. As years went by, he started working more on writing queries in SQL Server. He now has good level of knowledge in SQLServer, Oracle, MySQL and PostgreSQL as well. He is also one of the leading posters at www.sqlteam.com and a moderator at www.sql-server-performance.com. His T-sql blog is at http://beyondrelational.com/blogs/madhivanan


Anonymous said...

Why would I get errors for one of my columns not being included in the group by command when trying to use group by?

--CELKO-- said...

A GROUP BY partitions the table and then reduced each partition into a single row. That measn that the result can only contain partition attributes. grouping columns, constants, aggregate functions on the partiton and expressions that use these.

Anonymous said...

your example handles only part of the problem: one would need 'something else' to get the totals-row at the end - or identify it at all. in your example 'totals' cleverly is ordered behind 'test...'