随笔001:Group by 语法剪辑

基本语法:

GROUP BY [ALL] group_by_expression[,……n][WITH (CUBE|ROLLUP)]

参数说明:

ALL:用于指定包含所有组和结果集,甚至包含那些其中任何行都不满足Where子句指定的搜索条件的组和结果集;

group_by_expression:用于指定进行分组所依据的表达式,也称为组合列。

CUBE\ROLLUP:指定在结果集内不仅包含由Group by 提供的行,还包含汇总行。

常用用法:

例1、统计2008年产品编码为716到730的产品的销售量和销售额

USE AdventureWorks2008R2;
GO
SELECT ProductID,
 SUM(OrderQty) AS SubQty,SUM(LineTotal) AS SubTotal
FROM (
SELECT *
FROM Sales.SalesOrderDetail sod
WHERE  ProductID BETWEEN 716 AND 730
)Sale
WHERE ModifiedDate > CONVERT(DATETIME,'2008-1-1',120)
GROUP BY ProductID
ORDER BY ProductID

运行结果:

随笔001:Group by 语法剪辑

例2、Group by all 可以对数据表中所有的数据进行分组

USE AdventureWorks2008R2;
GO
SELECT ProductID,
 SUM(OrderQty) AS SubQty,SUM(LineTotal) AS SubTotal
FROM (
SELECT *
FROM Sales.SalesOrderDetail sod
WHERE  ProductID BETWEEN 716 AND 730
)Sale
WHERE ModifiedDate > CONVERT(DATETIME,'2008-1-1',120)
GROUP BY all ProductID
ORDER BY ProductID
运行结果:

随笔001:Group by 语法剪辑

例2和例1只是相差了“ALL”,但是在结果上却有所不同;

因为产品编码719,723,725,727,,729在select子句结果集Sale中存在数据,所以会出现在最后的结果集中。

但是因为这几个产品2008年没有销售记录所以其销售量和销售额为null。

例3、使用with cube 会对 Group by 所列出的所有分组字段进行汇总运算

USE AdventureWorks2008R2;
GO
SELECT ProductID,YEAR(Sale.ModifiedDate)S_Year,MONTH(Sale.ModifiedDate)S_Month,
 SUM(OrderQty) AS SubQty,SUM(LineTotal) AS SubTotal
FROM (
SELECT *
FROM Sales.SalesOrderDetail sod
WHERE  ProductID BETWEEN 716 AND 717
)Sale
WHERE ModifiedDate >= CONVERT(DATETIME,'2007-12-1',120)
AND ModifiedDate < CONVERT(DATETIME,'2008-3-1',120)
GROUP BY ProductID,YEAR(Sale.ModifiedDate),MONTH(Sale.ModifiedDate)
WITH cube
运行结果:

随笔001:Group by 语法剪辑

例4、使用with rollup 会对 Group by 所列出的分组字段从左往右(有时说从右往左)进行汇总运算

USE AdventureWorks2008R2;
GO
SELECT ProductID,YEAR(Sale.ModifiedDate)S_Year,MONTH(Sale.ModifiedDate)S_Month,
 SUM(OrderQty) AS SubQty,SUM(LineTotal) AS SubTotal
FROM (
SELECT *
FROM Sales.SalesOrderDetail sod
WHERE  ProductID BETWEEN 716 AND 717
)Sale
WHERE ModifiedDate >= CONVERT(DATETIME,'2007-12-1',120)
AND ModifiedDate < CONVERT(DATETIME,'2008-3-1',120)
GROUP BY ProductID,YEAR(Sale.ModifiedDate),MONTH(Sale.ModifiedDate)
WITH rollup
运行结果:

随笔001:Group by 语法剪辑

PS : Compute by 也有分组统计的作用,效果和Group by 略有不同,其语法如下:

[ COMPUTE     { { AVG | COUNT | MAX | MIN | STDEV | STDEVP | VAR | VARP | SUM }     ( expression ) } [ ,...n ]     [ BY expression [ ,...n ] ] ]

示例:

USE AdventureWorks2008R2;
GO
SELECT SalesPersonID, CustomerID, OrderDate, SubTotal, TotalDue
FROM Sales.SalesOrderHeader
ORDER BY SalesPersonID, OrderDate
COMPUTE SUM(SubTotal), SUM(TotalDue) BY SalesPersonID /*By后的分组字段必须出现在Order by 中*/
COMPUTE SUM(SubTotal), SUM(TotalDue) /*可多个Compute*/

运行结果(部分截图):

随笔001:Group by 语法剪辑

更多用法请查看微软msdn

上一篇:VUE 利用 webpack 给生产环境和发布环境配置不同的接口地址


下一篇:SharePoint服务器端对象模型 之 访问用户、用户组和权限(Part 1)