[英]Get row has Max value in MySQL?
我想获取staff_id
= AZ
具有此表的 MAX( step
) 值(名称:test)。
ID | general_id | 员工编号 | 步 |
---|---|---|---|
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.