Home > Database > Mysql Tutorial > body text

SQL2008新应用之T-SQL Grouping sets

WBOY
Release: 2016-06-07 15:13:13
Original
1485 people have browsed it

SQL SERVER 2005 使用了WITH CUBE 和WITH ROLLUP来显示统计信息,这是非常有用的功能,但它却不能提供很好的控制显示方法,但在katmai(sqlserver的下一个版本,估且称它mssql2008),以上的一切都会因 GROUPING SETS 引入而改变。使用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集合。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!