This article includes information about a feature from SQL Server 2008 (and up) - Group by extensions.
In SQL Server 2005 and earlier versions, we would have faced the situation that to get sum or avg or max based on more than one column.
The only way to go, GROUP BY with multiple queries and Union them at final which leads to performance issues.
— New Wings of Group By:
◦ GROUPING SETS,
◦ CUBE
◦ ROLLUP
Simply list all grouping sets that you need
SELECT Country,[State],City,
SUM (Population) AS [Population]
FROM @Population
GROUP BY GROUPING SETS ((Country,[State]),([State],City))
It produces all possible grouping sets that can be formed out of the elements listed in parentheses, including the empty grouping set
GROUP BY Country,[State],City WITH CUBE
Roll Up
The ROLLUP sub clause produces only the grouping sets that have business value, assuming a hierarchy between the elements.
GROUP BY Country,[State],City WITH ROLLUP