Is there any logic behind the reason to why the total grouping when using rollup will be "lvl" 3?..
example:
| col1 | col2 |
|---|---|
| id1 | 1 |
| id1 | 2 |
| id2 | 1 |
| id2 | 2 |
| id3 | 1 |
| id3 | 2 |
In cube method this is understandable as
level 0 is the "basic values" (my own term)such as "col1-ID1","col2-id1", "col3-id1" etc..,
level 1 will be the subtotal row of each basic value which means subtotal of ID1(1)+ID1(2) --> id1(3) for example.
level 2 will be the total of each combination which means subtotal of 1's and subtotal of 2's , in this example: 1- subtotal will be 3 and 2-subtotal will be 6
and level 3 will be the grand total of them all, in this example: 9
my explanation might not make any sense:) .. sorry
Is there any reason behind that skipping from lvl 0/1 straight to 3? or its just the way it is?
Summary: The grand total will be in the grouping set with the id the maximum value of the grouping set which is equal to 2(number of columns in the grouping set) - 1. Therefore, with 2 columns being cubed, the grand total is in 22-1 = 3 and, with 3 columns being cubed, the grand total is in 23-1 = 7.
Given the query:
Which, for the sample data:
Outputs:
You can see that when
GROUPING_ID(col1, col2)is:Nvalues for the second column).Mvalues for the first column and one value for the second column).Mvalues for the first column andNvalues for the second column givingN*Mtotal values); which will give you the grand total.If you had the sample data with 3 columns:
Then using
CUBEacross 3 columns:Outputs:
And will generate 23 = 8 levels (from 0 to 7) since there are all the possible combinations of grouping 3 columns and the grand-total will be in level 7; compared to 22 levels (0 to 3) when you are cubing 2 columns and the grand total is in level 3.
fiddle
Update
From the
SELECTdocumentation:CUBEgenerates all possible grouping sets;ROLLUPgenerates groups of the first 1 column then with the first 2 columns, 3 columns, ..., up toncolumns which is the same as theCUBEwhen the grouping sets are restricted to the 20-1, 21-1, 22-1, ..., 2n-1 (or more simply 0, 1, 3, 7, ... 2n-1).This means that
ROLLUPwill skip the grouping set with id 2 as that is grouping only by the 2nd column and that is not "one of the first n, n-1, n-2, ... 0 expressions" in theGROUP BYspecification.fiddle