Some tips when using GROUP BY in SQL Server
Using ROLLUP
The GROUP UP clause is used to group the results of aggregate functions according to a specified column. However, the GROUP BY clause doesn’t perform aggregate operations on multiple levels of a hierarchy. In that case, you can use the ROLL UP to calculate the subtotals and grand totals for a set of columns.
See example below:
1 | SELECT R.nameNode AS Register, COUNT(*) AS Mark_Numbers |
Results:

If you group by two different criterion, the result will give you the subtotal according to your criterion’s order. See example below:
1 | SELECT brand, category, SUM (sales) sales |
Results:

In this example, the query assumes that there is a hierarchy between brand & category, which is the brand > category.
See the following query:
1 | SELECT brand, category, SUM (sales) sales |
Results:

Using Grouping SETS (分组集)
A grouping set is a group of columns by which you group. It has the similar result as the GROUP BY ROLL UP.
When you use GROUP BY by default, it defines a grouping set (brand):
1 | SELECT brand, SUM (sales) sales |
When you use GROUP BY ROLLUP(brand, category), it defines a grouping sets ((brand, category), (brand), ()):
1 | SELECT brand, SUM (sales) sales |