MariaDB GROUP BY 关键字用于借助聚合函数(计数,最大值,最小值、总和、平均值 等)。 GROUP BY 关键字位于 SELECT 语句中的 WHERE 子句之后,并位于 ORDER BY 关键字之前。
语法
在 MariaDB 中使用 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 |