joins
不限于平等,你也可以加入<
。这意味着如果我们找到 ,我们可以根据所有小于 的max(hourly_rate)
结果加入该结果,并且也具有相同的,从那里我们只需要再次分组并从连接表中获取值。hourly_rate
max
project_code
max
select p1.project_code, max(p2.hourly_rate)
from
(select project_code, max(hourly_rate) r from project_team group by project_code) p1
left join project_team p2
on p2.project_code = p1.project_code and p2.hourly_rate < p1.r
group by project_code;
(这假设总是有第二高的(所有员工都有相同的费率,或者只有一名员工))
select p1.project_code, ifnull(max(p2.hourly_rate), p1.r)
from
(select project_code, max(hourly_rate) r from project_team group by project_code) p1
left join project_team p2
on p2.project_code = p1.project_code and p2.hourly_rate < p1.r
group by project_code;
如果没有第二高,这将给出最高值。
演示小提琴
select t.project_code, t.second_max_rate, t2.employee_id
from
(select p1.project_code, ifnull(max(p2.hourly_rate), p1.r) second_max_rate
from
(select project_code, max(hourly_rate) r from project_team group by project_code) p1
left join project_team p2
on p2.project_code = p1.project_code and p2.hourly_rate < p1.r
group by project_code) t
inner join project_team t2
on t.project_code = t2.project_code and t.second_max_rate = t2.hourly_rate
group by t.project_code;
此版本还包括员工 - 但请注意,它滥用 mysqls 的宽大处理group by
,您将获得 AN 员工,但无法保证如果有多个具有相同费率的员工,您将获得哪一个。