InterviewPrepKit

Home / SQL / Subqueries & CTEs

Department Payroll With a CTE

medium
Solving tips
  • A `WITH name AS (...)` common table expression names a subquery so you can reference it like a table, which keeps aggregate-then-filter queries readable.
  • Aggregate in the CTE, then join and filter in the outer query — this avoids repeating the `GROUP BY` and lets you filter on the aggregated columns without a `HAVING` clause.
  • `AVG` over an integer column returns numeric, so cast it if you want a whole-number average in the output.

Summarize payroll per department using a CTE, then keep only the departments whose total salary exceeds a threshold.

Schema

CREATE TABLE departments (
    id   integer PRIMARY KEY,
    name text    NOT NULL
);

CREATE TABLE employees (
    id            integer PRIMARY KEY,
    name          text    NOT NULL,
    department_id integer NOT NULL,
    salary        integer NOT NULL
);

Sample data — departments:

idname
10Engineering
20Sales
30Marketing

Sample data — employees:

idnamedepartment_idsalary
1Alice1090000
2Bob1070000
3Carol20100000
4Dave2060000
5Eve3050000
6Frank3040000

Task

Using a common table expression, compute each department’s total salary and average salary, then return the department_name, total_salary, and avg_salary (as an integer) for departments whose total salary is strictly greater than 150000.

Order by total_salary descending, then by department_name ascending. Expected columns: department_name, total_salary, avg_salary.

Expected output

Totals: Engineering 160000, Sales 160000, Marketing 90000. Marketing falls below the threshold and drops out.

department_nametotal_salaryavg_salary
Engineering16000080000
Sales16000080000
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.