T-SQL 多個分組集共有三種 GROUPING SETS, CUBE, 以及ROLLUP, 其中 CUBE和ROLLUP能夠當作是GROUPING SETS的簡寫版數據庫
示例數據庫下載:函數
http://files.cnblogs.com/files/haseo/TSQL2012.rarspa
GROUPING SETScode
列出全部你設置的分組集blog
SELECT shipperid, YEAR(shippeddate) AS shipyear, COUNT(*) AS numorders FROM Sales.Orders GROUP BY GROUPING SETS ( ( shipperid, YEAR(shippeddate) ), ( shipperid ), ( YEAR(shippeddate) ), ( ) );
CUBEseo
列出全部可能的分組集ip
SELECT shipperid , YEAR(shippeddate) AS shipyear , COUNT(*) AS numorders FROM Sales.Orders GROUP BY CUBE(shipperid, YEAR(shippeddate));
SELECT shipcountry , shipregion , shipcity , COUNT(*) AS numorders FROM Sales.Orders GROUP BY ROLLUP(shipcountry, shipregion, shipcity);
GROUPING()
該函數用來區分帶入的元素是否屬於分組的一部分, 返回0表示屬於,1表示不屬於ci
SELECT shipcountry , GROUPING(shipcountry) AS grpcountry , shipregion , GROUPING(shipregion) AS grpcountry , shipcity , GROUPING(shipcity) AS grpcountry , COUNT(*) AS numorders FROM Sales.Orders GROUP BY ROLLUP(shipcountry, shipregion, shipcity);
GROUPING_ID()rpc
該函數返回分組列的位圖(學過二進制的小夥伴都懂的,8421...以此類推) ,若是是0則全部分組字段都是分組的一部分,若是某個分組字段不是分組集的一部分則返回對應數字(既相關二進制位置1),最後進行彙總。it
以下代碼,若是shipcountry, shipregion, shipcity均是分組的一部分則返回0. 若是shipregion, shipcity 不在分組內,則是3 (0+2+1 )
SELECT GROUPING_ID(shipcountry, shipregion, shipcity) AS grp_id , shipcountry , shipregion , shipcity , COUNT(*) AS numorders FROM Sales.Orders GROUP BY ROLLUP(shipcountry, shipregion, shipcity);