简体   繁体   中英

Limiting MySQL select based on repeating column values?

Consider this schema:

create table Employee(
    id integer, 
    name varchar(100), 
    position varchar(100), 
    id_department integer
);

create table Salary(
    id_employee integer, 
    year integer, 
    month integer, 
    salary float
);

create table Department(
    id integer, 
    name varchar(100)
);

I want to gather Employees that are ranked between 3rd and 5th place based on their average yearly salary per department, but I am a bit stumped. After some searching, I couldn't quite find a solution that worked for me.

Here's what I have as of now:

SELECT Employee.*, avg_salary
FROM Employee
INNER JOIN (
    SELECT id_employee, sum(salary) / count(distinct(year)) as avg_salary 
    FROM Salary 
    GROUP BY id_employee
)
AS T on Employee.id = id_employee 
ORDER BY Employee.id_department, avg_salary;

This gets me correctly ranked Employees, but how do I get only the ones that are ranked 3-5 in their department?

I'm using MySQL 5.x, but upgrading to 8.x is not an issue.

In MySQL 8.0, one option is to use a ranking function; this requires turning your existing query to a subquery:

select *
from (
    select 
        e.*, 
        s.avg_salary, 
        row_number() over(partition by e.id_department order by s.avg_salary desc) rn
    from employee e
    inner join (
        select id_employee, sum(salary) / count(distinct(year)) as avg_salary 
        from salary 
        group by id_employee
    ) s on s.employee.id = e.id
) t
where rn between 3 and 5
order by id_department, avg_salary;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM