Given an Employee table with employee information including their company and salary, write a SQL solution to find the rows that contain the median salary of each company.
Key Requirements:
- Find median salary for each company separately
- When sorting salaries, break ties by
id(ascending order) - Return all rows that represent the median salary for their respective company
- If a company has even number of employees, return both middle values
The median is the middle value in a sorted list. For odd-sized groups, it's the single middle value. For even-sized groups, both middle values should be returned.
Table Schema
| Column Name | Type | Description |
|---|---|---|
id
PK
|
int | Primary key, unique employee identifier |
company
|
varchar | Company name where employee works |
salary
|
int | Employee salary amount |
Input & Output
| id | company | salary |
|---|---|---|
| 1 | A | 2341 |
| 2 | A | 341 |
| 3 | A | 15000 |
| 4 | A | 15000 |
| 5 | A | 15000 |
| 6 | A | 15000 |
| id | company | salary |
|---|---|---|
| 3 | A | 15000 |
| 4 | A | 15000 |
Company A has 6 employees. After sorting by salary then id: [341, 2341, 15000, 15000, 15000, 15000]. For even count (6), median positions are 3rd and 4th (rows with id=3 and id=4). Both have salary 15000.
| id | company | salary |
|---|---|---|
| 1 | B | 1000 |
| 2 | B | 2000 |
| 3 | B | 1000 |
| id | company | salary |
|---|---|---|
| 1 | B | 1000 |
Company B has 3 employees. After sorting by salary, then by id: [(1,1000), (3,1000), (2,2000)]. For odd count (3), median is the 2nd position, which is employee id=1 with salary 1000 (id=1 comes before id=3 due to tie-breaking).
Constraints
-
1 ≤ Employee.id ≤ 1000 -
1 ≤ company.length ≤ 100 -
1 ≤ salary ≤ 100000 - Each company has at least 1 employee