Quarterly Take-Home Pay and Latest-Period Drop Report
SQL & DataModel answerLast updated
Write a query that totals each employee's first-quarter take-home pay and flags those whose most recent paycheck fell below the one before it, with the percentage drop.
You are given two tables from a payroll system.
employees
| employee_id | hire_date | state |
|---|---|---|
| 101 | 2022-04-01 | CA |
| 102 | 2021-11-12 | NY |
| 103 | 2020-07-20 | TX |
payroll_transactions
| transaction_id | employee_id | paid_at | gross_pay | deductions |
|---|---|---|---|---|
| 1 | 101 | 2023-01-15 | 5000 | 500 |
| 2 | 101 | 2023-02-15 | 5000 | 550 |
| 3 | 102 | 2023-01-15 | 4500 | 400 |
| 4 | 103 | 2023-01-15 | 6000 | 600 |
| 5 | 102 | 2023-02-15 | 4500 | 450 |
Net pay for a transaction is gross_pay - deductions.
Task. Write a SQL query that, for each employee, reports:
- Their total net pay across the first calendar quarter of 2023 (1 January to 31 March).
- The percentage change in net pay between their two most recent pay periods.
Return only the employees whose net pay decreased between those two periods.
What to state and handle in your answer
- Say how you define a "pay period" (an employee may have more than one transaction on the same date).
- Say which two periods you compare and why.
- Decide what happens to employees with fewer than two pay periods.
- Be careful about integer division, a zero previous net pay, and date/timestamp boundaries.
Expected output columns: employee_id, Q1 total net pay, previous period net pay, latest period net pay, percentage change.
Hints
Hint 1
Collapse the data to one row per employee per pay date first, so that two payments on the same day count as a single period.
Hint 2
Use window functions over each employee: a SUM for the quarter total and ROW_NUMBER (or LAG) ordered by date descending to identify the latest and the previous period.
Hint 3
Compute the percentage as 100.0 * (latest - previous) / previous, protect against a zero denominator, and apply the date filter as a half-open range (>= Jan 1, < Apr 1) before any aggregation.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions to state up front
- Pay period. One distinct
paid_atdate per employee. Several transactions on the same day (for example a regular run plus a bonus) are summed into one period. Otherwise "the last two rows" could be two payments from the same day. - Which two periods. The two most recent periods inside Q1 2023, so the quarter total and the comparison describe the same window. If the interviewer wants the latest two overall, only the date filter moves.
- Percentage change =
(latest - previous) / previous * 100. A decrease meanslatest < previous. - Fewer than two periods. There is nothing to compare, so the employee is excluded (employee 103 in the sample).
- The
employeestable is not needed unless you also outputstateorhire_date. Do not join it for no reason.
Approach
Three stages, each as a CTE:
- Filter and aggregate. Keep only Q1 2023 rows and sum
gross_pay - deductionsper(employee_id, paid_at). - Rank and total. Over each employee,
SUM(net_pay)gives the quarter total, andROW_NUMBER() ... ORDER BY paid_at DESClabels the latest period 1 and the previous one 2. Because thern <= 2filter happens in a later step, the total still sees every Q1 period. - Pivot and compare. Conditional aggregation puts periods 1 and 2 side by side in one row, then compute the percentage and keep only decreases.
Solution (PostgreSQL / ANSI)
WITH q1_periods AS (
SELECT employee_id,
paid_at,
SUM(gross_pay - deductions) AS net_pay
FROM payroll_transactions
WHERE paid_at >= DATE '2023-01-01'
AND paid_at < DATE '2023-04-01' -- half-open: safe for timestamps
GROUP BY employee_id, paid_at
),
ranked AS (
SELECT employee_id,
net_pay,
SUM(net_pay) OVER (PARTITION BY employee_id) AS q1_net_pay,
ROW_NUMBER() OVER (PARTITION BY employee_id
ORDER BY paid_at DESC) AS rn
FROM q1_periods
),
latest_two AS (
SELECT employee_id,
MAX(q1_net_pay) AS q1_net_pay,
MAX(CASE WHEN rn = 1 THEN net_pay END) AS latest_net_pay,
MAX(CASE WHEN rn = 2 THEN net_pay END) AS previous_net_pay
FROM ranked
WHERE rn <= 2
GROUP BY employee_id
)
SELECT employee_id,
q1_net_pay,
previous_net_pay,
latest_net_pay,
ROUND(100.0 * (latest_net_pay - previous_net_pay)
/ NULLIF(previous_net_pay, 0), 2) AS pct_change
FROM latest_two
WHERE previous_net_pay IS NOT NULL
AND latest_net_pay < previous_net_pay
ORDER BY pct_change;
LAG variant. After q1_periods, compute LAG(net_pay) OVER (PARTITION BY employee_id ORDER BY paid_at) as the previous value, the windowed SUM as the quarter total, and ROW_NUMBER() ... DESC. Keep rn = 1, a non-null previous value, and net_pay < prev. This avoids the pivot, while the ROW_NUMBER plus pivot form makes "two most recent" explicit and is easier to extend (for example, latest vs. a rolling average).
Walkthrough on the sample
| employee | Jan net | Feb net | Q1 total | pct_change | kept? |
|---|---|---|---|---|---|
| 101 | 4500 | 4450 | 8950 | -1.11% | yes |
| 102 | 4100 | 4050 | 8150 | -1.22% | yes |
| 103 | 5400 | none | 5400 | none | no (one period) |
Ordered by largest drop, the result is 102 (-1.22%) and then 101 (-1.11%).
Why it is correct
- The date filter runs before aggregation, so totals only include Q1 rows.
- Grouping by
(employee_id, paid_at)makesrnrank real pay periods, not raw transactions, and guarantees no ties in the ordering. - The windowed
SUMis computed before thern <= 2filter, so the quarter total is complete. - Single-period employees have a NULL
previous_net_payand are removed explicitly, which documents intent.
Complexity
- Time: O(n log n) for n Q1 transactions, dominated by the sort/partition for the windows. An index on
(employee_id, paid_at)or(paid_at)turns the date filter into a range scan. - Space: O(n) for intermediate rows, O(e) for the result (e = employees).
Edge cases and common mistakes
- Integer division.
(4450 - 4500) / 4500is0in Postgres and SQL Server. Multiply by100.0first to force decimals. - Zero previous net pay. For example an unpaid period where deductions equal gross.
NULLIF(previous, 0)returns NULL instead of raising an error. - Negative net pay. Clawbacks can make the base negative, which flips the sign of the percentage. Flag this and consider filtering on absolute change instead.
BETWEENwith timestamps.BETWEEN '2023-01-01' AND '2023-03-31'drops2023-03-31 14:00. Use the half-open range.- Filtering before windowing. Applying
rn <= 2in the same step as theSUMwindow would shrink the quarter total to two periods. Keep them in separate stages. - Off-cycle runs. If bonus runs should not count as periods, you need a run-type column. Ask the interviewer.
- Same-date ties. Grouping solves this. Without it you would need a tiebreaker such as
transaction_id.
pandas equivalent
import pandas as pd
def q1_net_pay_decreases(tx: pd.DataFrame) -> pd.DataFrame:
tx = tx.copy()
tx["paid_at"] = pd.to_datetime(tx["paid_at"])
q1 = tx[(tx["paid_at"] >= "2023-01-01") & (tx["paid_at"] < "2023-04-01")].copy()
q1["net_pay"] = q1["gross_pay"] - q1["deductions"]
periods = (q1.groupby(["employee_id", "paid_at"], as_index=False)["net_pay"].sum()
.sort_values(["employee_id", "paid_at"]))
periods["q1_net_pay"] = periods.groupby("employee_id")["net_pay"].transform("sum")
periods["previous_net_pay"] = periods.groupby("employee_id")["net_pay"].shift(1)
latest = periods.groupby("employee_id").tail(1).rename(
columns={"net_pay": "latest_net_pay"})
latest = latest.dropna(subset=["previous_net_pay"])
latest = latest[latest["latest_net_pay"] < latest["previous_net_pay"]].copy()
latest["pct_change"] = (100 * (latest["latest_net_pay"] - latest["previous_net_pay"])
/ latest["previous_net_pay"]).round(2)
return (latest[["employee_id", "q1_net_pay", "previous_net_pay",
"latest_net_pay", "pct_change"]]
.sort_values("pct_change"))
The logic mirrors the SQL: filter, aggregate to periods, shift to get the previous value, take the last row per employee, then filter and compute the percentage. A zero previous value would produce inf or NaN here, so mask it if that can occur in your data.