KatInterview

Quarterly Take-Home Pay and Latest-Period Drop Report

SQL & DataModel answer
MediumModel answerSQL & Datasqlwindow-functionsaggregation

Last 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_idhire_datestate
1012022-04-01CA
1022021-11-12NY
1032020-07-20TX

payroll_transactions

transaction_idemployee_idpaid_atgross_paydeductions
11012023-01-155000500
21012023-02-155000550
31022023-01-154500400
41032023-01-156000600
51022023-02-154500450

Net pay for a transaction is gross_pay - deductions.

Task. Write a SQL query that, for each employee, reports:

  1. Their total net pay across the first calendar quarter of 2023 (1 January to 31 March).
  2. 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.