Total Salary Expenditure by Department
A company has several departments, and each employee is assigned to one department. You need to find out how much the company spends on salaries for each department.
Tables:
employees(employee_id INT PRIMARY KEY, name VARCHAR(100), salary NUMERIC(10, 2), department_id INT)departments(department_id INT PRIMARY KEY, department_name VARCHAR(100))
Return the department_name and the total salary spent by that department. The results should be ordered by department_name in ascending order.
Handle NULL department_id in employees by excluding them from any department's total. If a department has no employees, it should not appear in the results. Ties in department names are not possible as department_id is the primary key.
Tables
CREATE TABLE departments (
department_id INTEGER PRIMARY KEY,
department_name VARCHAR(100) NOT NULL
);
CREATE TABLE employees (
employee_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
salary NUMERIC(10, 2) NOT NULL,
department_id INTEGER
);Example data
INSERT INTO departments (department_id, department_name) VALUES (1, 'Engineering'), (2, 'Sales'), (3, 'Marketing'), (4, 'HR'); INSERT INTO employees (employee_id, name, salary, department_id) VALUES (101, 'Alice', 75000.00, 1), (102, 'Bob', 80000.00, 1), (103, 'Charlie', 60000.00, 2), (104, 'David', 55000.00, 2), (105, 'Eve', 70000.00, 3), (106, 'Frank', 50000.00, NULL);
Your query is also checked on hidden datasets with different data.
Hints
-- Calculate total salary for each department
SELECT
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.