-
leetcode - 569. Median Employee SalarySQL 문제풀이 2022. 8. 24. 18:30
난이도 : Hard
Table: Employee
+--------------+---------+ | Column Name | Type | +--------------+---------+ | id | int | | company | varchar | | salary | int | +--------------+---------+ id is the primary key column for this table. Each row of this table indicates the company and the salary of one employee.
Write an SQL query to find the median salary of each company.
Return the result table in any order.
The query result format is in the following example.
Example 1:
Input: Employee table: +----+---------+--------+ | id | company | salary | +----+---------+--------+ | 1 | A | 2341 | | 2 | A | 341 | | 3 | A | 15 | | 4 | A | 15314 | | 5 | A | 451 | | 6 | A | 513 | | 7 | B | 15 | | 8 | B | 13 | | 9 | B | 1154 | | 10 | B | 1345 | | 11 | B | 1221 | | 12 | B | 234 | | 13 | C | 2345 | | 14 | C | 2645 | | 15 | C | 2645 | | 16 | C | 2652 | | 17 | C | 65 | +----+---------+--------+ Output: +----+---------+--------+ | id | company | salary | +----+---------+--------+ | 5 | A | 451 | | 6 | A | 513 | | 12 | B | 234 | | 9 | B | 1154 | | 14 | C | 2645 | +----+---------+--------+
WITH sub AS ( SELECT * , ROW_NUMBER() OVER (PARTITION BY company ORDER BY salary) rnk , COUNT(*) OVER (PARTITION BY company) cnt FROM Employee ) SELECT id , company , salary FROM sub WHERE rnk BETWEEN cnt/2 AND cnt/2 + 1
Accepted (98.57%)
'SQL 문제풀이' 카테고리의 다른 글
leetcode - 1747. Leetflex Banned Accounts (0) 2022.08.26 leetcode - 571. Find Median Given Frequency of Numbers (0) 2022.08.24 leetcode - 1715. Count Apples and Oranges (0) 2022.08.24 leetcode - 1709. Biggest Window Between Visits (0) 2022.08.24 leetcode - 1699. Number of Calls Between Two Persons (0) 2022.08.24