Here is a very useful tip to generate sub totals and grand totals as part of the group by function
The video gives an example of how to use the ROLLUP extension in SQL Group by
for more tips subscribe to this channel or visit our page
https://selectdistinct.co.uk/tips-sql-server
#SQL #SQLTips #SQLROLLUP
Music from
https://www.bensound.com/
2. Did you know you can easily
add sub totals and grand totals
to your aggregated queries
In this example we are using a
date dimension table to return
the number of days per
calendar month
SELECT [Year], [quarter], [monthname],
count([date]) as [no of days]
FROM [dbo].[DimDate]
WHERE [Year] = 2022
GROUP BY [Year], [quarter], [monthname]
3. ROLLUP is an extension to the
group by clause
By default it adds a total row to
the columns you specify
SELECT [Year], [quarter], [monthname],
count([date]) as [no of days]
FROM [dbo].[DimDate]
WHERE [Year] = 2022
GROUP BY ROLLUP ([Year], [quarter], [monthname])
4. Totals and Sub Totals by
default are labelled as NULL
It is worth changing these with
a bit of logic
We can use coalesce to give
these totals a specific name
SELECT coalesce ([Year],'Total All Years') as [Year]
, coalesce ([quarter],'Total All Quarters') as [Quarter]
, coalesce ([monthname], 'Total All Months') as [Month]
, count([date]) as [no of days]
FROM [dbo].[DimDate]
WHERE [Year] = 2022
GROUP BY ROLLUP ([Year], [quarter], [monthname])
5. This technique is really powerful and can
be added to group by queries with little
effort
It can be used with other aggregation
functions (SUM, COUNT, AVG, MAX, MIN)
Partial rollups can also be used to avoid
certain sub totals in this example
SELECT coalesce ([Year],'Total All Years') as [Year]
, coalesce ([quarter],'Total All Quarters') as [Quarter]
, coalesce ([monthname], 'Total All Months') as [Month]
, count([date]) as [no of days]
FROM [dbo].[DimDate]
WHERE [Year] = 2022
GROUP BY [Year], ROLLUP ([quarter], [monthname])