The first three high-sector wages for all employees - LeetCode

Employee table contains information on all employees, each employee has its corresponding job number Id, Name Name, Salary and wages department number DepartmentId.

+----+-------+--------+--------------+
| Id | Name  | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 85000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
| 5  | Janet | 69000  | 1            |
| 6  | Randy | 85000  | 1            |
| 7  | Will  | 70000  | 1            |
+----+-------+--------+--------------+

Department table contains information about all sectors of the company.

+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+

Write a SQL query to find all employees in each department to obtain three high wages. For example, given the above table, the query results should be returned:

+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Max      | 90000  |
| IT         | Randy    | 85000  |
| IT         | Joe      | 85000  |
| IT         | Will     | 70000  |
| Sales      | Henry    | 80000  |
| Sales      | Sam      | 60000  |
+------------+----------+--------+

Explanation:

IT department, Max received the highest wages, Randy and Joe have got the second-highest wages, Will salary ranked third. Sales (Sales) only two employees, the highest wages Henry, Sam salary ranked second.

 

My answer:

# Write your MySQL query statement below

select
    d.Name as Department,
    temp.Name Employee,
    temp.Salary
from
    Department d left join
    (select
        e.DepartmentId,
        e.Name,
        @curRank := if (@prevDept = DepartmentId, if(@prevSal = e.Salary, @curRank, @curRank + 1), 1) as Rank,
        @prevSal := e.Salary as Salary,
        @prevDept := e.DepartmentId
    from Employee e,
    (select @prevDept := null, @curRank := 0, @prevSal := null) t
    order by e.DepartmentId, e.Salary desc
    ) temp on d.Id = temp.DepartmentId
where temp.Rank <= 3

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/department-top-three-salaries

: )

Guess you like

Origin www.cnblogs.com/gotodsp/p/11959050.html