【SQL23】查询出每个项目中经验最丰富(experience_years最大)的员工

查询出每个项目中经验最丰富(experience_years最大)的员工

有如下两张表
project

pro_id      emp_id
1           1
1           2
1           3
2           1
2           4

employee

emp_id      name        exp_year
1           Lisi        3
2           Wangwu      2
3           Zhaoliu     3
4           Zhangsan    2

结果如下:

pro_id      emp_id      exp_year
1           1           Lisi
1           3           Zhaoliu
2           1           Lisi

解决:

select pro_id
      ,emp_id
      ,name
  from (
        select a.pro_id
              ,a.emp_id
              ,b.name
              ,b.exp_year
              ,rank() over(partition by a.pro_id order by b.exp_year desc) as rn
          from project a
          left join employee b
            on a.emp_id = b.emp_id
        )a
 where rn = 1
;

pro_id	emp_id	name
1	1	Lisi
1	3	Zhaoliu
2	1	Lisi


备注:建表和数据
create table project(pro_id int,emp_id int);
insert into project values(1,1);
insert into project values(1,2);
insert into project values(1,3);
insert into project values(2,1);
insert into project values(2,4);

create table employee(emp_id int,name varchar(30),exp_year int);
insert into employee values(1,'Lisi',3);
insert into employee values(2,'Wangwu',2);
insert into employee values(3,'Zhaoliu',3);
insert into employee values(4,'Zhangsan',2);

 

你可能感兴趣的:(每日一练)