1、使用TABLESAMPLE来返回随机行:
SELECT [SalesQuotaKey]
,[EmployeeKey]
,[DateKey]
,[CalendarYear]
,[CalendarQuarter]
,[SalesAmountQuota]
FROM [AdventureWorksDW2008R2].[dbo].[FactSalesQuota]
TABLESAMPLE SYSTEM (50 PERCENT)
TABLESAMPLE的功能是从某个数据源返回一定百分比的随机行;但是这个百分比是表数据页的百分比不是数据行的百分比,一旦选中了一个样本页,那么页中的所有行都会返回;由于页的填充状态各不相同,所以返回行的数量也不一样;
2、使用CUBE汇总数据:
SELECT [CalendarYear]
,SUM([SalesAmountQuota])
FROM [AdventureWorksDW2008R2].[dbo].[FactSalesQuota]
GROUP BY CUBE (CalendarYear)
CUBE为结果集增加行,根据GROUP BY子句中的列来汇总总数值;提供了一种为分组列求和的简单方法;
3、使用GROUP BY ROLLUP 来汇总数据:
SELECT [CalendarYear]
,[DateKey]
,SUM([SalesAmountQuota])
FROM [AdventureWorksDW2008R2].[dbo].[FactSalesQuota]
GROUP BY ROLLUP (CalendarYear,DateKey)
GROUP BY ROLLUP用来根据GROUP BY子句中列的次序来增加层次化的数据汇总;
4、使用分组集创建自定义汇总:
SELECT [CalendarYear]
,[DateKey]
,SUM([SalesAmountQuota])
FROM [AdventureWorksDW2008R2].[dbo].[FactSalesQuota]
GROUP BY GROUPING SETS ((CalendarYear),(DateKey))
GROUPING SETS操作符允许在单个查询中定义不同的聚合分组,避免了使用union all 将多个查询附加到一起; GROUPING SETS之后是圆括号和列名的分组,每一个分组都括在圆括号中;
5、GROUPING的使用
SELECT [CalendarYear],DateKey,
CASE WHEN GROUPING(CalendarYear) = 0 AND GROUPING(DateKey) = 1 THEN 'CalendarYear'
WHEN GROUPING(CalendarYear) = 1 AND GROUPING(DateKey) = 0 THEN 'DateKey'
WHEN GROUPING(CalendarYear) = 1 AND GROUPING(DateKey) = 1 THEN 'Total'
ELSE 'Regular'
END TYPE
,SUM([SalesAmountQuota])
FROM [AdventureWorksDW2008R2].[dbo].[FactSalesQuota]
GROUP BY GROUPING SETS ((CalendarYear),(DateKey))
GROUPING
可以简单地评估一行是否为聚合的产物;
如果GROUPING函数返回值为1(真),表示NULL不是实际的数据值,而是聚合操作的结果;
6、GROUPING_ID的使用
GROUPING_ID在功能上相当于将多个GROUPING函数的结果串接成二进制数,返回的是这个二进制数对应的十进制数
SELECT [CalendarYear],DateKey,
CASE GROUPING_ID(CalendarYear,DateKey)
WHEN 1 THEN 'CalendarYear'
WHEN 2 THEN 'DateKey'
WHEN 3 THEN 'Total'
WHEN 0 then 'Other'
END TYPE
,SUM([SalesAmountQuota])
FROM [AdventureWorksDW2008R2].[dbo].[FactSalesQuota]
GROUP BY CUBE(CalendarYear,DateKey)
ORDER BY CalendarYear,DateKey