InterviewPrepKit

Home / SQL / Joins

Join With Aggregation: Headcount and Average Salary per Department

medium
Solving tips
  • Join first to attach the label you want to group by, then GROUP BY that label.
  • GROUP BY the department name (or id) and put every non-aggregated selected column in the GROUP BY.
  • Wrap AVG in ROUND to control decimal places, and remember COUNT(*) counts rows per group.

Summarize each department’s team size and pay.

Schema

CREATE TABLE departments (
    id        INT PRIMARY KEY,
    dept_name VARCHAR(50) NOT NULL
);

CREATE TABLE employees (
    id      INT PRIMARY KEY,
    name    VARCHAR(50) NOT NULL,
    dept_id INT REFERENCES departments(id),
    salary  NUMERIC(10,2) NOT NULL
);

departments

iddept_name
10Engineering
20Sales
30Marketing

employees

idnamedept_idsalary
1Alice10120000.00
2Bob10100000.00
3Carol2090000.00
4Dave2095000.00
5Eve2085000.00
6Frank3070000.00

Task

For each department that has at least one employee, return dept_name, employee_count (number of employees), and avg_salary (average salary rounded to 2 decimals). Order by employee_count descending, then dept_name ascending.

Expected output

dept_nameemployee_countavg_salary
Sales390000.00
Engineering2110000.00
Marketing170000.00
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.