0

我想计算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;
4

1 回答 1

2

joins不限于平等,你也可以加入<。这意味着如果我们找到 ,我们可以根据所有小于 的max(hourly_rate)结果加入该结果,并且也具有相同的,从那里我们只需要再次分组并从连接表中获取值。hourly_ratemaxproject_codemax

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 员工,但无法保证如果有多个具有相同费率的员工,您将获得哪一个。

于 2015-04-17T05:17:58.847 回答