SQL SERVER 2005 使用了WITH CUBE 和WITH ROLLUP來顯示統計信息,這是非常有用的功能,但它卻不能提供很好的控制顯示方法,但在katmai(sqlserver的下一個版本,估且稱它mssql2008),以上的一切都會因GROUPING SETS引入而改變。使用GROUPING SETS,我們會獲得想要統計信息。
在這里,給出一個實例:
語句A
| 以下是引用片段: select ProductKey,OrderDateKey,CustomerKey,PromotionKey, sum(UnitPrice)SumUnitPrice, sum(OrderQuantity)SumOrderQuantity from dbo.FactInternetSales group by ProductKey,OrderDateKey,CustomerKey,PromotionKey |
語句B
| 以下是引用片段: select ProductKey,OrderDateKey,CustomerKey,PromotionKey, sum(UnitPrice)SumUnitPrice, sum(OrderQuantity)SumOrderQuantity from dbo.FactInternetSales group by grouping sets( ( ProductKey,OrderDateKey,CustomerKey,PromotionKey ) ) |
看到上面的例子大家或許會猜想出一二,我將給大家展示一下grouping sets的特別之處。
例子:
當我們在不同的集合中使用分組,則GROUPING SETS將會非常有用。
| 以下是引用片段: select ProductKey,OrderDateKey,CustomerKey,PromotionKey, sum(UnitPrice)SumUnitPrice, sum(OrderQuantity)SumOrderQuantity from dbo.FactInternetSales group by grouping sets( --Aggregate by all columns in the select clause ( ProductKey, OrderDateKey, CustomerKey, PromotionKey ), --Aggregate by a subset of the columns in the select clause ( ProductKey, OrderDateKey, CustomerKey ), () --ALL aggregation ); |
第一個grouping sets以(ProductKey,OrderDateKey,CustomerKey,PromotionKey)為單位分組聚集UnitPrice & OrderQuantity
第二個grouping sets以(ProductKey,OrderDateKey,CustomerKey)為單位分組聚集UnitPrice & OrderQuantity
第三個grouping sets直接聚集UnitPrice & OrderQuantity,相當于一條匯總數據
說明:grouping sets 沒有使用的select子句中的列將會返回NULL值。
整個結果集對每一個GROUPING SETS做運算。
下面是一個執行結果的截圖

看一下最后一句,這句就是第三個grouping sets,它在每一個非聚集列中都顯示NULL,你同樣能看到在第二個grouping sets中,沒有使用到的列也顯示NULL。
總結:
本文講解了grouping sets使用方法,我的第一印象是它的自定義化比較強,很靈活,我們甚至可以自己聚合出OLAP集合。
新聞熱點
疑難解答