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
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
METHOD 1: Using ROLLUP
select coalesce(name,'Total') as name, SUM(amount) as amount from @t
group by name
with rollup
METHOD 2: Using UNIONALL
select name, SUM(amount) as amount from @t
group by name
union all
select 'Total',SUM(amount) from @t
OUTPUT
3 comments:
Why would I get errors for one of my columns not being included in the group by command when trying to use group by?
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.
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...'
Post a Comment