·天新网首页·加入收藏·设为首页
首页|笔记本|手机|数码相机|摄像机|MP3/MP4|主板|内存|显示器|办公|打印机|下载|开发|汽车|学院|业界
硬件|台式机|数码|数字家庭|投影仪|GPS/CPU|显卡|硬盘|服务器|网络|一体机|驱动|源码|游戏|考试|报价
SQL2008新应用之T-SQL Grouping sets
http://dev.21tx.com 2007年09月20日

  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集合。

上一篇: 分析各种数据库优点 帮你做出准确选择
下一篇: 动态创建MSSQL数据库表存储过程

Google
 
热点文章
关于我们 | 联系我们 | 广告服务 | 工作机会 | 版权声明 | 欢迎投稿 | 网站地图
Copyright © 2000-2008 , www.21tx.com , All Rights Reserved .
© 晨新科技 版权所有 Created by TXSite.net