在本教程中,您将学习如何使用sql max
函数查找组中的最大值。
sql提供max()
函数,用于在一组值中查找最大值。 以下是max
函数的语法。
max(expression)
max
函数忽略null
值。
与sum,count和avg函数不同,distinct
选项不适用于max
函数。
我们将使用employees
表来演示max
函数的工作原理。
desc employees ;
+---------------+--------------+------+-----+---------+----------------+
| field | type | null | key | default | extra |
+---------------+--------------+------+-----+---------+----------------+
| employee_id | int(11) | no | pri | null | auto_increment |
| first_name | varchar(20) | yes | | null | |
| last_name | varchar(25) | no | | null | |
| email | varchar(100) | no | | null | |
| phone_number | varchar(20) | yes | | null | |
| hire_date | date | no | | null | |
| job_id | int(11) | no | mul | null | |
| salary | decimal(8,2) | no | | null | |
| manager_id | int(11) | yes | mul | null | |
| department_id | int(11) | yes | mul | null | |
+---------------+--------------+------+-----+---------+----------------+
10 rows in set
以下select
语句返回employees
表中员工的最高薪水。
select
max(salary)
from
employees;
+-------------+
| max(salary) |
+-------------+
| 24000 |
+-------------+
1 row in set
要获得薪水最高的员工,请使用子查询,如下所示:
select
employee_id,
first_name,
last_name,
salary
from
employees
where
salary = (
select
max(salary)
from
employees
);
执行上面查询语句,得到以下结果 -
+-------------+------------+-----------+--------+
| employee_id | first_name | last_name | salary |
+-------------+------------+-----------+--------+
| 100 | steven | lee | 24000 |
+-------------+------------+-----------+--------+
1 row in set
子查询返回最高薪水,外部查询获得薪水等于最高薪水的员工。
2.1. sql max与group by示例
我们通常将max
函数与group by
子句结合使用来查找每个分组的最大值。
例如,可以使用max
函数查找每个部门中员工的最高薪水,如下所示:
select
department_id,
max(salary)
from
employees
group by
department_id;
执行上面查询语句,得到以下结果:
要在结果中包含部门名称,我们将employees
表与departments
表连接,如下所示:
select
d.department_id,
department_name,
max(salary)
from
employees e
inner join departments d on d.department_id = e.department_id
group by
e.department_id;
执行上面查询语句,得到以下结果:
2.2. sql max带有order by示例
与其他聚合函数一样,要根据max
函数的结果对结果集进行排序,必须将max
函数放在order by
子句中。
例如,以下语句返回每个部门中员工的最高工资,并根据最高工资对结果集进行排序。
select
d.department_id,
department_name,
max(salary)
from
employees e
inner join departments d on d.department_id = e.department_id
group by
e.department_id
order by
max(salary) desc;
执行上面查询语句,得到以下结果:
2.3. sql max带有having示例
在max
函数使用having
子句将条件添加到group by
子句汇总分组。
例如,要获得具有最高薪水大于12000
的员工的部门,请在max
函数使用having
子句,如下所示:
select
d.department_id,
department_name,
max(salary)
from
employees e
inner join departments d on d.department_id = e.department_id
group by
e.department_id
having
max(salary) > 12000;
执行上面示例代码,得到以下结果:
+---------------+-----------------+-------------+
| department_id | department_name | max(salary) |
+---------------+-----------------+-------------+
| 2 | 市场营销 | 13000 |
| 8 | 销售 | 14000 |
| 9 | 行政人员 | 24000 |
+---------------+-----------------+-------------+
3 rows in set
在本教程中,我们将演示如何使用max
函数来查找一分组值中的最大值。