The first time I saw such an SQL statement, I couldn't understand it, and I used the following uncommonly used
Clustering function: Grouping
The rollup operator used to summarize data
Select
Case grouping (O. customerid) When 0 then O. customerid else '(total)' End
As allcustomerssummary,
Case grouping (OD. orderid) When 0 then OD. orderid else-1 end
As individualcustomersummary,
Sum (OD. Quantity * OD. unitprice) as price
From orders o, [Order Details] OD
Where year (O. orderdate) = 1998 and OD. orderid = O. orderid
Group by O. customerid, OD. orderid with Rollup
Order by allcustomerssummary
Check the help of SQL Server to find out, amazing, there is such a powerful thing, can not help but think of the previous Crystal Report, the original SQL server can achieve such a function.
1. Use cube to summarize data
The result set generated by the cube operator is a multi-dimensional dataset. A multi-dimensional dataset is an extension of fact data. Fact data is the data that records individual events. The extension is created on the columns that the user intends to analyze. These columns are called dimensions. A multi-dimensional dataset is a result set that contains all possible combinations of cross tables for each dimension.
The cube operator is specified in the group by clause of the SELECT statement. The statement selection list should contain dimension columns and aggregate function expressions. The dimension column and keyword with cube should be specified for group. The result set contains all possible combinations of values in the dimension column, and the aggregated values in the basic rows that match the combination of these dimension values.
For example, a simple tableInventoryIncluding:
Item color Quantity ------------------ ---------------------- -------------------------- table blue 124 table red 223 chair blue 101 chair red 210
The returned results of the following queries includeItemAndColorAll possible combinationsQuantitySubtotal:
Select item, color, sum (Quantity) as qtysumfrom inventorygroup by item, color with cube
The following is the result set:
Item color qtysum ------------------ ---------------------- ------------------------ chair blue 101.00 chair red 210.00 Chair (null) 311.00 table blue 124.00 table red 223.00 table (null) 347.00 (null) 658.00 (null) blue 225.00 (null) Red 433.00
We focus on the following:
Chair (null) 311.00
This line reportsItemThe value in the dimension is the subtotal of all rows of chair. PairColorThe dimension returns a null value, indicating that the aggregation reported by this row includesColorThe row whose dimension is any value.
Table (null) 347.00
This line is similar, but the report isItemThe mean value of a dimension is the subtotal of all rows in the table.
(Null) 658.00
This row reports the total number of multidimensional datasets.ItemAndColorThe dimension value is null, indicating that all values in the two dimensions are aggregated in the row.
(Null) Blue 225.00 (null) Red 433.00
The two rows reportedColorSubtotal of a dimension. In the two rowsItemAll dimension values are null, indicating that the aggregated data comes fromItemThe row whose dimension is any value.
Use grouping to differentiate null values
The null value generated by the cube operation brings about a problem: how to distinguish between the null value generated by the cube operation and the null value returned from the actual data? This problem can be solved by the grouping function. If the value in the column comes from the fact data, the grouping function returns 0. If the value in the column is null generated by the cube operation, 1 is returned. In the cube operation, the generated null represents the whole value. You can use the 'select' statement to replace the generated null with the string 'all. Because null in the fact data indicates that the data value is unknown, the SELECT statement can also be decoded as the returned string unknown to replace null from the fact data. For example:
Select case when (grouping (item) = 1) then 'all' else isnull (item, 'unknown ') end as item, case when (grouping (color) = 1) then 'all' else isnull (color, 'unknown ') end as color, sum (Quantity) as qtysumfrom inventorygroup by item, color with cube
Multi-dimensional dataset
The cube operator can be used to generateNDimension, that is, a cube with any number of dimensions. Only one dimension cube can be used to generate a total. For example:
Select case when (grouping (item) = 1) then 'all' else isnull (item, 'unknown ') end as item, sum (Quantity) as qtysumfrom inventorygroup by item with cubego
The result set returned by this select statement is displayedItemReturns the subtotal of each value inItemTotal of all values in:
Item qtysum -------------------- -------------------------- chair 311.00 table 347.00 all 658.00
Select statements containing cubes with many dimensions may generate large result sets because these statements generate rows for all combinations of values in all dimensions. These large result sets may contain too much data and are not easy to read and understand. One solution to this problem is to place the SELECT statement in the View:
Create view invcube asselect case when (grouping (item) = 1) then 'all' else isnull (item, 'unknown ') end as item, case when (grouping (color) = 1) then 'all' else isnull (color, 'unknown ') end as color, sum (Quantity) as qtysumfrom inventorygroup by item, color with cube
Then you can use this view to query only the dimension values you are interested in:
Select * From invcubewhere item = 'chair' and color = 'all' item color qtysum ------------------------------------ -------------------- chair all 311.00 (1 row (s) affected)
2. Use rollup to summarize data
The rollup operator is useful when generating reports that contain subtotal and aggregate. The result set generated by the rollup operator is similar to the result set generated by the cube operator. For more information.
The difference between cube and rollup is:
- The result set generated by cube displays the aggregation of all the combinations of the values in the selected column.
- The result set generated by rollup displays the aggregation of a certain hierarchy of values in the selected column.
For example, a simple tableInventoryIncluding:
Item color Quantity ------------------ ---------------------- -------------------------- table blue 124 table red 223 chair blue 101 chair red 210
The following query generates a subtotal report:
Select case when (grouping (item) = 1) then 'all' else isnull (item, 'unknown ') end as item, case when (grouping (color) = 1) then 'all' else isnull (color, 'unknown ') end as color, sum (Quantity) as qtysumfrom inventorygroup by item, color with rollupitem color qtysum -------------------- explain chair blue 101.00 chair red 210.00 chair all 311.00 table blue 124.00 table red 223.00 table all 347.00 all 658.00 (7 row (s) affected)
If the rollup keyword in the query is changed to cube, the cube result set is the same as the preceding result, but the following two rows are returned at the end of the result set:
All Blue 225.00 all red 433.00
Cube operation isItemAndColorThe median value may be combined to generate rows. For example, Cube not only reports andItemValue chair combinationColorAll possible combinations of values (red, blue, and red + blue), and reportColorValue redItemAll possible combinations of values (Chair, table, and Chair + Table ).
For each value in the right column of the Group by clause, the rollup operation does not report all possible combinations of values in the left column (or left column. For example, rollup does notColorValue reportItemAll possible combinations of values.
The result set of The rollup operation is similar to the result set returned by compute by. However, rollup has the following advantages:
- Rollup returns a single result set; compute by returns multiple result sets, while multiple result sets are added to the application.ProgramCodeComplexity.
- Rollup can be used in server cursors; compute by cannot.
- Sometimes, the execution plan generated by the query optimizer for rollup is more efficient than that generated by compute.
3. Grouping
Is an aggregate function that generates an additional column. When a row is added using the cube or rollup operator, the output value of the appended column is 1, when the added row is not produced by cube or rollup, the value of the appended column is 0.
Grouping is allowed only in the selection list associated with the group by clause that contains the cube or rollup operator.
Syntax
Grouping( Column_name)
Parameters
Column_name
Is the column in the group by clause used to check the null values of cube or rollup.
Return type
Int
Note
Grouping is used to distinguish between the null values returned by cube and rollup and the standard null values. A special application that returns NULL as the result of a cube or rollup operation. It acts as a placeholder for a column in the result set, meaning "all ".
Example
In the following exampleRoyaltyGroup and aggregateAdvance. Apply the grouping functionRoyaltyColumn.
Use pubsselect royalty, sum (advance) 'total advance ', grouping (royalty) 'grp'
From titles group by royalty with Rollup
Result set inRoyaltyTwo null values are displayed. The first null represents the null group obtained from this column in the table. The second null is in the summary row added by the rollup operation. The summary row displays allRoyaltyGroupAdvanceAndGRP1 is used in the column.
The following is the result set:
Royalty total advance GRP --------- ------------------- --- null 0 10 57000.0000 0 12 2275.0000 0 14 4000.0000 0 16 7000.0000 0 24 25125.0000 0 null 95400.0000 1
3. Grouping
Is an aggregate function that generates an additional column. When a row is added using the cube or rollup operator, the output value of the appended column is 1, when the added row is not produced by cube or rollup, the value of the appended column is 0.
Grouping is allowed only in the selection list associated with the group by clause that contains the cube or rollup operator.
Syntax
Grouping( Column_name)
Parameters
Column_name
Is the column in the group by clause used to check the null values of cube or rollup.
Return type
Int
Note
Grouping is used to distinguish between the null values returned by cube and rollup and the standard null values. A special application that returns NULL as the result of a cube or rollup operation. It acts as a placeholder for a column in the result set, meaning "all ".
Example
In the following exampleRoyaltyGroup and aggregateAdvance. Apply the grouping functionRoyaltyColumn.
Use pubsselect royalty, sum (advance) 'total advance ', grouping (royalty) 'grp'
From titles group by royalty with Rollup
Result set inRoyaltyTwo null values are displayed. The first null represents the null group obtained from this column in the table. The second null is in the summary row added by the rollup operation. The summary row displays allRoyaltyGroupAdvanceAndGRP1 is used in the column.
The following is the result set:
Royalty total advance GRP --------- ------------------- --- null 0 10 57000.0000 0 12 2275.0000 0 14 4000.0000 0 16 7000.0000 0 24 25125.0000 0 null 95400.0000 1
3. Grouping
Is an aggregate function that generates an additional column. When a row is added using the cube or rollup operator, the output value of the appended column is 1, when the added row is not produced by cube or rollup, the value of the appended column is 0.
Grouping is allowed only in the selection list associated with the group by clause that contains the cube or rollup operator.
Syntax
Grouping( Column_name)
Parameters
Column_name
Is the column in the group by clause used to check the null values of cube or rollup.
Return type
Int
Note
Grouping is used to distinguish between the null values returned by cube and rollup and the standard null values. A special application that returns NULL as the result of a cube or rollup operation. It acts as a placeholder for a column in the result set, meaning "all ".
Example
In the following exampleRoyaltyGroup and aggregateAdvance. Apply the grouping functionRoyaltyColumn.
Use pubsselect royalty, sum (advance) 'total advance ', grouping (royalty) 'grp'
From titles group by royalty with Rollup
Result set inRoyaltyTwo null values are displayed. The first null represents the null group obtained from this column in the table. The second null is in the summary row added by the rollup operation. The summary row displays allRoyaltyGroupAdvanceAndGRP1 is used in the column.
The following is the result set:
Royalty total advance GRP --------- ------------------- --- null 0 10 57000.0000 0 12 2275.0000 0 14 4000.0000 0 16 7000.0000 0 24 25125.0000 0 null 95400.0000 1
The introduction to grouping, rollup, and cube comes from the help of the Chinese version of SQL Server2000.