Interview Questions/SQL/Salary Quartile Distribution Per Department

Salary Quartile Distribution Per Department

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given an Employees table. Using a recursive CTE to generate the 4 quartile bucket numbers (1-4), compute for each department and quartile: how many employees fall in that bucket (via NTILE(4)), and the min and max salary in that bucket. Return (department, quartile, employee_count, min_sal, max_sal) for ALL 4 quartiles of every department, even if a quartile has 0 employees (show NULL for min/max in that case). Order by department, then quartile. Table: Employees

Column NameTypeDescription
idINTPrimary key
nameVARCHAREmployee name
departmentVARCHARDepartment name
salaryINTAnnual salary

Database Schema (Inferred)

Employees

Column NameExample Value
id1
nameA
departmentEng
salary90000

Example

Employees

idnamedepartmentsalary
1AEng90000
2BEng85000
3CEng70000
4DEng60000
5EEng55000
6FSales50000
7GSales45000
8HSales40000
9ISales38000
10JHR80000
11KHR75000
12LHR65000

Output

departmentquartileemployee_countmin_salmax_sal
EngQ125500060000
EngQ217000070000
EngQ318500085000
EngQ419000090000
HRQ116500065000
HRQ217500075000
HRQ318000080000
HRQ40NULLNULL
SalesQ113800038000
SalesQ214000040000
SalesQ314500045000
SalesQ415000050000

Explanation:

Use a recursive CTE to generate bucket numbers 1-4. CROSS JOIN with distinct departments. LEFT JOIN the NTILE(4) result. NTILE distributes rows as evenly as possible, adding extras to earlier buckets when the count is not divisible by 4.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Employees

idnamedepartmentsalary
1AEng90000
2BEng85000
3CEng70000
4DEng60000
5EEng55000
6FSales50000
7GSales45000
8HSales40000
9ISales38000
10JHR80000
11KHR75000
12LHR65000

Output

departmentquartileemployee_countmin_salmax_sal
EngQ125500060000
EngQ217000070000
EngQ318500085000
EngQ419000090000
HRQ116500065000
HRQ217500075000
HRQ318000080000
HRQ40NULLNULL
SalesQ113800038000
SalesQ214000040000
SalesQ314500045000
SalesQ415000050000