SQL Server (Transact-SQL) GROUP BY 关键字用于借助聚合函数 (Count,Max,MIN, SUM, AVG 等)进行查询。 GROUP BY 关键字位于 SELECT 语句中的 WHERE 子句之后,位于 ORDER BY 关键字之前。
语法
在 SQL Server (Transact-SQL) 中使用 GROUP BY 关键字的语法如下:
SELECT column1, column2
FROM table_name
WHERE condition(s)
GROUP BY column1, column2
ORDER BY column1, column2;
示例:
考虑名为 Employee 的数据库表,包含以下记录:
EmpID | Name | City | Age | Salary |
---|---|---|---|---|
1 | John | London | 25 | 3000 |
2 | Marry | New York | 24 | 2750 |
3 | Jo | Paris | 27 | 2800 |
4 | Kim | Amsterdam | 30 | 3100 |
5 | Ramesh | London | 28 | 3000 |
6 | Huang | London | 28 | 2800 |
GROUP BY 单列:要查找 Employee 表中按年龄(降序)排序的不同年龄段的员工人数,查询为:
SELECT Age, Count(Name) AS Number_of_Employee
FROM Employee
GROUP BY Age
ORDER BY Age DESC;
这将产生如下结果:
Age | Number_of_Employee |
---|---|
30 | 1 |
28 | 2 |
27 | 1 |
25 | 1 |
24 | 1 |
GROUP BY 多列: 查找Employee 按城市和年龄排序的表,查询为:
SELECT City, Age, AVG(Salary) AS AverageSalary
FROM Employee
GROUP BY City, Age
ORDER BY City, Age;
这将产生如下所示的结果:
City | Age | AverageSalary |
---|---|---|
Amsterdam | 30 | 3100.0 |
London | 25 | 3000.0 |
London | 28 | 2900.0 |
New York | 24 | 2750.0 |
Paris | 27 | 2800.0 |