Search

Department Top Three Salaries

Input: Employee table: +----+-------+--------+--------------+ | 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: +----+-------+ | id | name | +----+-------+ | 1 | IT | | 2 | Sales | +----+-------+ Output: +------------+----------+--------+ | Department | Employee | Salary | +------------+----------+--------+ | IT | Max | 90000 | | IT | Joe | 85000 | | IT | Randy | 85000 | | IT | Will | 70000 | | Sales | Henry | 80000 | | Sales | Sam | 60000 | +------------+----------+--------+ Explanation: In the IT department: - Max earns the highest unique salary - Both Randy and Joe earn the second-highest unique salary - Will earns the third-highest unique salary In the Sales department: - Henry earns the highest salary - Sam earns the second-highest salary - There is no third-highest salary as there are only two employees
Plain Text
볡사
νšŒμ‚¬μ˜ μž„μ›λ“€μ€ νšŒμ‚¬μ˜ 각 λΆ€μ„œμ—μ„œ λˆ„κ°€ κ°€μž₯ λ§Žμ€ λˆμ„ λ²„λŠ”μ§€ ν™•μΈν•˜λŠ” 데 관심이 μžˆλ‹€.
ν•œ λΆ€μ„œμ˜ κ³ μ†Œλ“μžλŠ” ν•΄λ‹Ή λΆ€μ„œμ˜ μƒμœ„ 3개의 고유 κΈ‰μ—¬λ₯Ό λ°›λŠ” μ§μ›μž…λ‹ˆλ‹€.
각 λΆ€μ„œμ—μ„œ κ³ μ†Œλ“μžμΈ 직원을 μ°ΎκΈ° μœ„ν•΄ SQL 쿼리λ₯Ό μž‘μ„±ν•©λ‹ˆλ‹€.
κ²°κ³Ό ν…Œμ΄λΈ”μ„ μž„μ˜μ˜ μˆœμ„œλ‘œ λ°˜ν™˜ν•©λ‹ˆλ‹€.
쿼리 κ²°κ³Ό ν˜•μ‹μ€ λ‹€μŒ μ˜ˆμ œμ™€ κ°™μŠ΅λ‹ˆλ‹€.
β€’
RANK(), DENSE_RANK()
SELECT t.department , t.employee , t.salary FROM ( SELECT department.name AS department , employee.name AS employee , employee.salary AS salary , DENSE_RANK() OVER (PARTITION BY departmentid ORDER BY salary DESC) AS dr FROM employee JOIN department ON employee.departmentid = department.id ) AS T WHERE t.dr <= 3 ;
SQL
볡사