20. Median Salary by Job Title
Beginner Mode
Objective
Write an SQL query to calculate the median salary for each job title within a company. The median salary is the middle value in the list of salaries for a particular job title when the list is sorted in ascending order. If the number of salaries is even, the median is the average of the two middle numbers. Your query should return the job titles and their corresponding median salaries, rounded to two decimal places, in descending order of the median salary.
Additional information
The employees table:
| Column | Type | Description |
|---|---|---|
| id | INT | The unique identifier for each employee |
| name | VARCHAR | The name of the employee |
| job_title | VARCHAR | The job title of the employee |
| salary | INT | The salary of the employee |
Constraints:
- The number of employees can range from 1 to 10^5.
- The salary values are positive integers.
Clarifications:
- Ensure that the median salary is calculated correctly based on the number of employees for each job title.
- The results should be sorted in descending order of the median salary.
- If multiple job titles have the same median salary, order them alphabetically by job title.
Examples
Example 1:
Output:
Input:
| employees | |||
|---|---|---|---|
| id | job_title | name | salary |
| 1 | Software Engineer | John | 85000 |
| 2 | Software Engineer | Alice | 95000 |
| 3 | Software Engineer | Bob | 90000 |
| 4 | Product Manager | Sarah | 110000 |
| 5 | Product Manager | Mike | 120000 |
| 6 | Designer | Emma | 75000 |
| 7 | Designer | David | 70000 |
| 8 | Designer | Lisa | 72000 |
| job_title | median_salary |
|---|---|
| Product Manager | 115000 |
| Software Engineer | 90000 |
| Designer | 72000 |
Code Environment
Sign in or try as guest to run your code.
Essential
SQL 0/33
Git 0/15
Spark 0/20
Snowflake 0/22
Python 0/24
Need more practice in this area? Explore more questions →
ActivisionBlizzard
TCS
X
Accenture
Adobe
Google
LinkedIn
Samsung
Datadog
Wix
Dropbox
Meta
OpenAI
Hulu
Uber
DoorDash
Anthropic
Amazon
Vercel
Crypto.Com
Zscaler
DeutscheBank
Apple
GoDaddy
BMW
PayPal
Snowflake
AMD
Twilio
Atlassian
JPMorgan
NVIDIA
IBM
Databricks
Coinbase
Cisco
Robinhood
Twitter
Microsoft
Palantir
Netflix
VMware
Cloudflare
Stripe
Capital One
Splunk
Intel
SAP
Tesla
GitHub
JaneStreet
Bloomberg
Salesforce
Elastic
CGI
UBS
GitLab
Ubisoft
Slack
Nintendo
EY
Kayak
Lyft
Airbnb
Walmart
Revolut
Visa
Okta
HashiCorp
Instacart
Mastercard