AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > SQL Server

SQL2008新应用之T-SQL Grouping sets

51自学网 http://www.51zixue.net

  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
  用GROUPING SETS来表达同一逻辑性语句

  语句B

以下是引用片段:
  select ProductKey,OrderDateKey,CustomerKey,PromotionKey,
  sum(UnitPrice)SumUnitPrice,
  sum(OrderQuantity)SumOrderQuantity
  from dbo.FactInternetSales
  group by
  grouping sets(
  (
  ProductKey,OrderDateKey,CustomerKey,PromotionKey
  )
  )
  语句B使用GROUPING SETS,grouping sets中的内容与语句A中的group by一致,并且它也返回相同数据。

  看到上面的例子大家或许会猜想出一二,我将给大家展示一下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:

  第一个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集合。

 

 

 
上一篇:SQL Server 2005:你应知道的13件事  下一篇:轻松掌握DB2数据库中的数据移动