# The Org Chart in Numbers

> Headcount by department, sliced by quarter. Every seat accounted for.

Canonical URL: <https://datadriven.io/problems/department_quarterly_pivot>

Domain: SQL · Difficulty: hard · Seniority: L4

## Problem

Show employee count broken down by department and fiscal quarter. For each department, create columns Q1 through Q4 showing how many metric entries exist per quarter. If a quarter has no entries, show 0.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests manual pivoting using conditional aggregation. Transforming rows into columns (Q1 through Q4) is a common reporting pattern that interviewers use to test CASE WHEN inside aggregate functions.

---

### Break down the requirements

#### Step 1: Group by department

`GROUP BY department` produces one row per department.

#### Step 2: Pivot quarters into columns

Use `SUM(CASE WHEN fiscal_quarter = 'Q1' THEN 1 ELSE 0 END)` for each quarter column.

---

### The solution

**Manual pivot with conditional aggregation**

```sql
SELECT
    department,
    SUM(CASE WHEN fiscal_quarter = 'Q1' THEN 1 ELSE 0 END) AS q1,
    SUM(CASE WHEN fiscal_quarter = 'Q2' THEN 1 ELSE 0 END) AS q2,
    SUM(CASE WHEN fiscal_quarter = 'Q3' THEN 1 ELSE 0 END) AS q3,
    SUM(CASE WHEN fiscal_quarter = 'Q4' THEN 1 ELSE 0 END) AS q4
FROM employee_metrics
GROUP BY department
```

> **Cost Analysis**
>
> Scan of 15K rows. Trivially fast. Four conditional sums in one pass.

> **Interviewers Watch For**
>
> Whether the candidate uses the manual CASE WHEN pivot (portable) vs CROSSTAB (PostgreSQL-specific). Strong candidates can discuss both approaches.

> **Common Pitfall**
>
> Forgetting ELSE 0 in the CASE expression would produce NULL instead of 0 for quarters with no data. The prompt specifies showing 0 for missing quarters.

---

## Common follow-up questions

- How would you handle dynamic quarters (not just Q1-Q4)? _(CROSSTAB or dynamic SQL; manual CASE does not scale to unknown values.)_
- What if the data also has fiscal_year and you need year-quarter columns? _(Tests nested CASE or multi-level GROUP BY.)_
- How does CROSSTAB work in PostgreSQL? _(Tests knowledge of the tablefunc extension.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/department_quarterly_pivot)
- [SQL Interview Questions](https://datadriven.io/sql-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.