网站主页   操作系统    网络工程    服务器    网页制作    数据库    程序开发    网络安全    办公软件   
  栏目导航
讲座日期: 本周六下午1点30分 抢座
讲座地点: 北大青鸟马甸校区
主讲老师: 王老师 金牌讲师
讲座主题: 网络安全
讲座内容: 检测、防御、黑客信息,如何过滤不安全的网站,如何防御黑客的进攻。
订座电话: 010-82011432/33
  您当前位置:主页 > 网络学院 > 数据库 > SQL Serves >

SQL2008新应用之T-SQL Grouping sets




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

 

 

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

·华腾教育 SQL Server存储过程中初学者简单操作示例 ·浅谈SQL Server数据类型最大值
·[SQL Server]连接中的常见错误原因分析 ·获取SQL Server数据库里表的占用容量大小
·SQL SERVER 2000 中的标识值获取函数 ·SQL Server 2005:你应知道的13件事
·轻松掌握SQL Server数据同步技术 ·SQL Server数据库和XML标识语言的集成
·解析SQL Server identity列的操作方法 ·运用SQL Server安全模型来保护数据

Copyright © 2002-2015 版权所有
学校地址:北京市海淀区西三旗建材城中路29号北大青鸟
招生热线:010-82011433/32 京公网安备110102004704  京ICP备05043413号 京公网安备110102004704