[SQL23] Query the most experienced (experience_years) employees in each project

Find out the most experienced employees (the largest experience_years) in each project

There are the following two tables
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

The results are as follows:

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

solve:

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);

 

Guess you like

Origin blog.csdn.net/debimeng/article/details/104200721