sql 与group by 是用来数据分组的,下面我们看数据库表称为EmployeeHours存放每一个公司员工的 日常 时间:
Employee | Date | Hours |
John Smith | 5/6/2004 | 8 |
Allan Babel | 5/6/2004 | 8 |
Tina Crown | 5/6/2004 | 8 |
John Smith | 5/7/2004 | 9 |
Allan Babel | 5/7/2004 | 8 |
Tina Crown | 5/7/2004 | 10 |
John Smith | 5/8/2004 | 8 |
Allan Babel | 5/8/2004 | 8 |
Tina Crown | 5/8/2004 | 9 |
如果公司经理想要得到的所有员工的所有工作时间叠加,他需要执行下列SQL语句:
SELECT SUM (Hours)
FROM EmployeeHours
但是,如果经理想要得到他的员工为每个所有时间的总和?
为此,他需要修改他的SQL查询和使用SQL的GROUP BY语句:
SELECT Employee, SUM (Hours)
FROM EmployeeHours
GROUP BY Employee
The result of the SQL expression above will be the following:
Employee | Hours |
John Smith | 25 |
Allan Babel | 24 |
Tina Crown | 27 |
该SQL的GROUP BY子句可以用于其他SQL聚合函数,例如的SQL的AVG:
SELECT Employee, AVG(Hours)
FROM EmployeeHours
GROUP BY Employee
Employee | Hours |
John Smith | 8.33 |
Allan Babel | 8 |
Tina Crown | 9 |
在我们的雇员表的日期专栏中,我们也可以 分组
SELECT Date, SUM(Hours)
FROM EmployeeHours
GROUP BY Date
Here is the result of the above SQL expression:
Date | Hours |
5/6/2004 | 24 |
5/7/2004 | 27 |
5/8/2004 | 25 |
时间: 2024-09-30 01:47:38