Giving a name to the Total Row when using GROUP BY ROLLUP in SQL

Are looking to give some extra context to your SQL query output before you deliver to business users WITHOUT the use of Excel?

A colleague of yours would like to see the sales per person including a GRAND TOTAL row. Using GROUP BY ROLLUP ( ColumnName ) you can easily create this, But this will leave an ugly blank, as a description for the grand total row. Yuck! Luckily this is easily fixed by adding a simple CASE WHEN to your code.

Below is an example.  

SELECT
	 case 
		when grouping(Person) = 1 then 'GrandTotalRecords'
		else Person
	 end as Person
	,count(*) as TotalRecords
FROM [TEST].[dbo].[SimpelAantalPerPersoon]
group by rollup(Person)
order by Person

Leave Comment

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *