N062-M3 Tier 5 · Expert · medium hr · Helix Systems

Return each `department_id`, its `dept_salary` (combined salary across all of its records), and its `pct_of_total` (its share of the company-wide salary expenditure expressed as a percentage)

Part of Choosing Between Subqueries, CTEs, and Joins in SQL

The problem

Scenario: Helix Systems' finance team is reviewing each department's share of the company's total salary expenditure across every salary record on file.

Task: Write a query to return each department_id, its dept_salary (combined salary across all of its records), and its pct_of_total (its share of the company-wide salary expenditure expressed as a percentage).

Assumptions:

  • A department's dept_salary is the combined amount across every salary record belonging to its employees.
  • A department's pct_of_total is dept_salary divided by the combined salary across every department in the result, multiplied by 100.
  • The result covers only departments with at least one salary record.

Output:

  • One row per qualifying department.
  • Columns in this order: department_id, dept_salary, pct_of_total.
Schema · hr 4 tables
departments
id integer
name text
location text
budget numeric
salaries
id integer
employee_id integer
amount numeric
effective_date date
end_date? date
employees
id integer
name text
email text
department_id integer
manager_id? integer
hire_date date
title text
is_active boolean
job_history
id integer
employee_id integer
title text
department_id integer
start_date date
end_date? date

Run previews · Check grades

Write a query, then run it to see results here.

Worked solution Try it yourself first
Solution query
WITH
  dept_totals AS (
    SELECT
      e.department_id,
      SUM(s.amount) AS dept_salary
    FROM
      salaries s
      JOIN employees e ON e.id = s.employee_id
    GROUP BY
      e.department_id
  )
SELECT
  dt.department_id,
  dt.dept_salary,
  dt.dept_salary * 100.0 / (
    SELECT
      SUM(dept_salary)
    FROM
      dept_totals
  ) AS pct_of_total
FROM
  dept_totals dt

The shape

A CTE produces one row of dept_salary per department, and a scalar subquery in the SELECT list reads the company-wide total off the same CTE to compute each department's share. The CTE is referenced twice, which makes the named intermediate worth its space.

Clause by clause

  • WITH dept_totals AS (SELECT e.department_id, SUM(s.amount) AS dept_salary FROM salaries s JOIN employees e ON e.id = s.employee_id GROUP BY e.department_id) joins salaries to employees and totals by department. One row per department that has any salary record.
  • SELECT dt.department_id, dt.dept_salary, dt.dept_salary * 100.0 / (SELECT SUM(dept_salary) FROM dept_totals) AS pct_of_total FROM dept_totals dt reads the CTE as the outer driver and references it a second time inside the scalar subquery to obtain the company-wide sum. The scalar subquery returns a single number that is the same for every outer row, so it acts as the constant denominator.
  • The multiplier 100.0 (not 100) keeps the division in numeric territory so the percentage carries a fractional part instead of being truncated.

Why this and not SUM(dept_salary) OVER ()

SELECT department_id, dept_salary, dept_salary * 100.0 / SUM(dept_salary) OVER () AS pct_of_total FROM dept_totals produces identical results in one pass and is the more compact form. Both are correct. The scalar-subquery shape used here makes the company-wide denominator read as a named operation against the CTE, which can be easier to debug if the percentage logic gets more complicated later.

The trap

The denominator is "the combined salary across every department in the result," not "the company-wide salary across every row in salaries." Those numbers are the same here because every salary belongs to a department that ends up in the CTE, but the wording matters if a future filter on the outer query reduces which departments appear. A common mistake is computing the denominator off the raw salaries table instead of off the CTE, which would silently desynchronize numerator and denominator the moment the outer query's row set changes.

You practiced computing per-department totals once in a CTE and reusing that same CTE in a scalar subquery for the company-wide denominator — a shape only a CTE supports without recomputing.

How you actually get good at SQL

Reading explains SQL. Writing it, over and over with instant feedback, is what makes you fluent.

That's the whole SQLMaxx loop: 600+ real problems, instant AI feedback, mastery you can actually see, and spaced review that won't let you forget.

A stack of SQL practice problem cards, the top card showing an employees table.
615 problems · 66 concepts

Real problems. Not toy examples.

615 hand-built problems spanning all 66 concepts, from basic SELECTs to window functions, built on real schemas and real business questions, the kind you'll actually get asked on the job. Enough reps to make SQL automatic.

A retro computer showing a SQL query marked correct with a green checkmark.
Instant AI feedback

Write a query. Know if it's right in one second.

No copying an answer and hoping it clicked. The AI grader checks your real query against real data, catches exactly what's wrong, and explains the fix in plain English, like a senior analyst reading over your shoulder on every problem.

A circular mastery progress dial filling from blue to green, the SQLMaxx diamond at its center.
Mastery tracking

Stop guessing whether you actually know it.

SQLMaxx tracks every concept and shows you what you've mastered and what's still shaky. Your skills fill in one concept at a time, so 'I think I get joins' becomes something you can prove.

A SQL query editor circled by a blue return arrow with a clock, scheduled to come back for review.
Spaced review

Learn it once. Keep it for good.

Most of what you learn this week fades by next week. So when a concept comes due for review, SQLMaxx hands you a fresh problem to solve from a blank editor, not a flashcard to re-read. A research-backed spaced-repetition algorithm (FSRS) times each return for right before you'd forget, so your SQL is still there months later, when the interview or the job actually needs it.

Practice, feedback, mastery, review. That's the loop that turns reading into real skill.

Start free

No account, no credit card. Start solving in under a minute.