The result set generated by Cube:cube shows aggregations for all combinations of values in the selected column.
The result set generated by Rollup:rollup shows the aggregation of a hierarchy of values in the selected column.
GROUPING: When a row is added by the cube or ROLLUP operator, the function causes the output value of the additional column to be 1, and when the row is not added by the cube or ROLLUP operator, the function causes the output value of the additional column to be 0.
Create a temporary table first:
1 Create Table#Temp2 (3Namevarchar( -) not NULL,4Coursevarchar( -)NULL,5Scoresint NULL6 )7 8 Insert into#Temp9 Select 'Little Red','SQL',' -' Union Ten Select 'Little Red','C #',' -' Union One Select 'Xiao Ming','SQL',' the' Union A Select 'Xiao Ming','C #',' the' Union - Select 'Xiao Li','SQL',' the' Union - Select 'Xiao Li','C #',NULL the - Select * from#Temp
With CUBE:
1 Select name, course,sum2 from #temp3 Group by name, course 4 with Cube
Group by name and class, then group by name and class.
PS: The classification is based not on the order in select, but on the order in group by.
Let's look at the results in a different order:
1 Select name, course,sum2 from #temp3Groupby Course, name 4 with Cube
Groups of classes and names are grouped together and grouped by class and name.
The result set generated by cube shows aggregations for all combinations of values in the selected column.
With ROLLUP:
1 Select name, course,sum2 from #temp3Groupby name, course 4 with rollup
1 Select name, course,sum2 from #temp3Groupby Course, name 4 with rollup
The result set generated by ROLLUP shows the aggregation of a hierarchy of values in the selected column.
So what is this one level structure? Look at the data above, when grouped by name, divided into three groups (excluding the last line total), when the course first grouped, divided into two groups (excluding the last line total).
This particular hierarchy I suspect should be related to group by's grouping order.
GROUPING:
The combination of grouping with rollup (same as with Cube)
1 Select name, course,sum(score),GROUPING2 from #temp3 Group by name, course 4 with rollup
When grouping is specified as "name", only the last line is added with rollup.
1 Select name, course,sum(score),GROUPING2 from #temp3 Group by name, course 4 with rollup
When grouping is specified as a "course", the third, sixth, Nineth, and last lines are added with rollup.
When a row is added by the cube or ROLLUP operator, the function causes the output value of the additional column to be 1, and when the row is not added by the cube or ROLLUP operator, the function causes the output value of the additional column to be 0.
1 Selectname,2 Case when GROUPINGName=1 3 Then 'Total' 4 Else 5 Case when GROUPINGCourse=1 6 Then ' Subtotal' 7 ElseCourseEnd 8 Endcourses,9 sum(Score)Ten from#Temp One Group byName, course A withRollup
Application of SQL Server with ROLLUP, with CUBE, grouping statement