Skip to content
Quantoros

Return departmentid, name, salary, and a running total of salary within the department ordered by salary descending…

SQLLevel: IntermediateWindow functions

Return department_id, name, salary, and a running total of salary within the department ordered by salary descending then name.

Table definitions (from the source exercise):

CREATE TABLE employees(emp_id INTEGER PRIMARY KEY, name TEXT, department_id INTEGER, manager_id INTEGER, salary INTEGER, hire_date TEXT, job_title TEXT, gender TEXT);
Hints
  • Define one output row and the source-table keys.
  • Check duplicates, NULLs and the order of filtering and aggregation.

Answer

Approach: SUM(salary) OVER (PARTITION BY dept ORDER BY salary DESC, name).

SELECT department_id, name, salary,
       SUM(salary) OVER (PARTITION BY department_id
                         ORDER BY salary DESC, name) AS running_total
FROM employees;

The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.

Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT

Related questions