获取行在 MySQL 中的最大值?
Get row has Max value in MySQL?
我想获得 staff_id
= AZ
具有此 table(名称:测试)的 MAX(step
) 值。
id
general_id
staff_id
step
1
4
A1
1
2
4
AZ
2
3
4
A2
3
4
5
A3
1
5
5
A4
2
6
5
AZ
3
SELECT MAX(step) AS STEP, staff_id
FROM test AS t
WHERE staff_id = AZ
GROUP BY general_id
对于只有一名员工,您可以使用 order by
和 limit
:
select *
from test
where staff_id = 'AZ'
order by step desc limit 1
如果您想同时为多个员工执行此操作,则一个选项使用相关子查询:
select *
from test t
where t.step = (select max(t1.step) from test t1 where t1.staff_id = t.staff_id)
此方法的另一个特点是它允许顶部连接(如果有)。
或者,在 MySQL 8.0 中,您可以使用 window 函数:
select *
from (
select t.*,
rank() over(partition by staff_id order by step desc) rn
from test t
) t
where rn = 1
我想获得 staff_id
= AZ
具有此 table(名称:测试)的 MAX(step
) 值。
id | general_id | staff_id | step |
---|---|---|---|
1 | 4 | A1 | 1 |
2 | 4 | AZ | 2 |
3 | 4 | A2 | 3 |
4 | 5 | A3 | 1 |
5 | 5 | A4 | 2 |
6 | 5 | AZ | 3 |
SELECT MAX(step) AS STEP, staff_id
FROM test AS t
WHERE staff_id = AZ
GROUP BY general_id
对于只有一名员工,您可以使用 order by
和 limit
:
select *
from test
where staff_id = 'AZ'
order by step desc limit 1
如果您想同时为多个员工执行此操作,则一个选项使用相关子查询:
select *
from test t
where t.step = (select max(t1.step) from test t1 where t1.staff_id = t.staff_id)
此方法的另一个特点是它允许顶部连接(如果有)。
或者,在 MySQL 8.0 中,您可以使用 window 函数:
select *
from (
select t.*,
rank() over(partition by staff_id order by step desc) rn
from test t
) t
where rn = 1