SQL LeetCode: 569. Median Employee Salary

Pallavi Mirajkar Dantkale
2 min readApr 7, 2021

569. Median Employee Salary

Hard

The Employee table holds all employees. The employee table has three columns: Employee Id, Company Name, and Salary.

+-----+------------+--------+
|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 |
+-----+------------+--------+

Write a SQL query to find the median salary of each company. Bonus points if you can solve it without using any built-in SQL functions.

+-----+------------+--------+
|Id | Company | Salary |
+-----+------------+--------+
|5 | A | 451 |
|6 | A | 513 |
|12 | B | 234 |
|9 | B | 1154 |
|14 | C | 2645 |
+-----+------------+--------+

WITH CTE AS (
SELECT
Id, Company, salary,
row_number() OVER (partition by Company order by salary) as rank_id,
count(ID) OVER (partition by Company) as count_ID
FROM
Employee )

SELECT
ID,
Company,
Salary
FROM CTE
WHERE (CASE
WHEN count_ID%2!=0 THEN rank_id=(count_ID+1)/2
ELSE rank_id = count_ID/2 OR rank_id = (count_ID/2)+1
END)

--

--

Pallavi Mirajkar Dantkale

QA Engineer / Data Analyst — Highly committed to Quality Assurance and data analysis, advocate for quality and add the right value to the organization.