在Select语句中,GROUP BY 语句,其作用是用于结合合计函数,根据一个或多个列对结果集进行分组。换言之,Group By 子句用于对结果集进行分组,并对每一组数据进行汇总计算。
标准语法如下:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
简单的说,该语法其实就是:
Group By [列名] [HAVING 条件表达式]
Group By按“列名”指定的列进行分组,将该列列值相同的记录组成一组,并对每一组进行汇总计算。每一组生成一条记录。若有“HAVING 条件表达式”,则表示对生成的组进行筛选。
请注意,不能对ntext、text、image 或 bit 列使用GROUP BY或HAVING,除非它们所在的函数返回的值属于其他数据类型。这样的函数包括 SUBSTRING 和 CAST。
应用举例
SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer
SELECT Customer,OrderDate,SUM(OrderPrice) FROM Orders GROUP BY Customer,OrderDate
SELECT ColumnA,
MAX(ColumnB) AS MaxB,
SUM(ColumnC) AS SumC
FROM TableX
GROUP BY ColumnA
select DepartmentID as '部门名称',COUNT(*) as '个数' from BasicDepartment group by DepartmentID
SELECT OrderYear, COUNT(DISTINCT CustomerID) AS NumCusts
FROM (SELECT YEAR(OrderDate), CustomerID
FROM dbo.Orders) AS D(OrderYear, CustomerID)
GROUP BY OrderYear
下面再看一种情况,结婚Having一起使用的。
SELECT AName COUNT(B) FROM TABLE GROUP BY A HAVING COUNT(B)>6