21. Salary Comparison with CTE Aggregation
Beginner Mode
Objective
Write an SQL query to find employees whose salaries are above the average salary of their respective departments. The query should return the employee's name, department name, employee's salary, and the average salary of the department rounded to two decimal places. The results should be ordered by department name and then by employee salary in descending order.
Additional information
- Each department has a unique ID.
- Each employee belongs to only one department.
- The output should include only those employees who earn more than the average salary of their department.
- The salary values should be rounded to two decimal places in the output.
- The results must be sorted first by department name in ascending order, then by employee salary in descending order.
Constraints:
- The number of employees will be between 1 and 10^4.
- The number of departments will be between 1 and 10^3.
Clarifications:
- You can assume that the department names and employee names are unique within their respective tables.
- Locations of the departments are not relevant for this query.
Examples
Example 1:
Output:
Input:
| departments | ||
|---|---|---|
| id | location | name |
| 1 | NYC | Engineering |
| 2 | LA | Sales |
| employees | |||
|---|---|---|---|
| department_id | id | name | salary |
| 1 | 1 | John | 75000 |
| 1 | 2 | Sarah | 65000 |
| 2 | 3 | Michael | 85000 |
| 2 | 4 | Lisa | 72000 |
| 2 | 5 | David | 68000 |
| department_avg_salary | department_name | employee_name | salary |
|---|---|---|---|
| 70000 | Engineering | John | 75000 |
| 75000 | Sales | Michael | 85000 |
Code Environment
Sign in or try as guest to run your code.
Essential
SQL 0/33
Spark 0/20
Snowflake 0/22
Python 0/24
Need more practice in this area? Explore more questions →
Crypto.Com
Revolut
Accenture
Adobe
Google
LinkedIn
Samsung
Datadog
Wix
Dropbox
Meta
OpenAI
Hulu
Uber
X
DoorDash
Anthropic
Amazon
ActivisionBlizzard
Vercel
Zscaler
DeutscheBank
Apple
GoDaddy
GitLab
BMW
PayPal
Snowflake
AMD
Twilio
Atlassian
JPMorgan
NVIDIA
IBM
Databricks
Coinbase
Cisco
Robinhood
Twitter
Microsoft
Palantir
Netflix
VMware
Cloudflare
Stripe
Lyft
Salesforce
GitHub
Bloomberg
Airbnb
Walmart
SAP
HashiCorp
Instacart
Mastercard
Intel
Visa
Tesla