我想计算每个项目中员工的第二高hourly_rate
。
但我不知道我在哪里做错了
我关注的表结构:
project_team: project_code (FK), employee_id (FK), hourly_rate
这是我的查询,它给出的唯一一条记录也不是第二高的。
注意:我有3个项目,每个项目都有很多员工。
SELECT * FROM (
SELECT * FROM project_team GROUP BY project_code ORDER BY hourly_rate DESC LIMIT 1,1
) e;
答案 0 :(得分:2)
joins
不限于平等,您也可以加入<
。这意味着,如果我们找到max(hourly_rate)
,那么我们可以根据所有hourly_rate
小于max
并且具有相同project_code
的{{1}}来加入该结果。在那里我们只需要再次分组并从连接表中获取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;
此版本还包括员工 - 请注意,它会滥用与group by
相关的mysqls leniancy,您将获得AN员工,但如果有多个员工,您无法保证会获得哪一个以相同的速度。