Find Departments with Above Average Salary Spending
A company wants to analyze its salary distribution. They need to identify departments that are spending more on salaries than the company's average department spending.
Tables:
Employees(employee_id INT PRIMARY KEY, department_id INT, salary NUMERIC(10, 2))Departments(department_id INT PRIMARY KEY, department_name VARCHAR(50))
Return the department_name for departments whose total salary cost exceeds the average total salary cost across all departments. If no departments meet this criterion, return an empty result set. Handle NULL salaries by treating them as 0 for calculations. If there's a tie in average spending, include all tied departments. Order the results alphabetically by department_name.
Tables
CREATE TABLE Departments (
department_id INTEGER PRIMARY KEY,
department_name VARCHAR(50) NOT NULL
);
CREATE TABLE Employees (
employee_id INTEGER PRIMARY KEY,
department_id INTEGER REFERENCES Departments(department_id),
salary NUMERIC(10, 2)
);Example data
INSERT INTO Departments (department_id, department_name) VALUES (1, 'Engineering'), (2, 'Sales'), (3, 'Marketing'), (4, 'HR'); INSERT INTO Employees (employee_id, department_id, salary) VALUES (101, 1, 90000.00), (102, 1, 85000.00), (103, 2, 70000.00), (104, 2, 75000.00), (105, 3, 60000.00), (106, 3, 65000.00), (107, 4, 50000.00), (108, 1, 95000.00);
Your query is also checked on hidden datasets with different data.
Hints
Similar problems
- Find Students with Above-Average GPA in Their DepartmentMedium
- Find Interns with Above Average SalaryMedium
- Students with Above Average GPA in Their DepartmentMedium
- Internship Offers by Company and DepartmentMedium
- Intern Stipend by Department and Start DateMedium
- Average Score per Student GroupMedium
More in: SQL and Databases problems
-- Select the department names that spend above average
SELECT department_name
FROM Departments
Your query runs on the example tables shown with the problem, then on hidden datasets when you submit.
Write standard SQL. MySQL habits work too: IFNULL, IF, YEAR(), DATE_FORMAT, GROUP_CONCAT, `backticks` and LIMIT 5, 10. It runs on PostgreSQL, so integer division keeps whole numbers (5 / 2 = 2): write 5.0 / 2 for 2.5.