KatInterview

Pairing Clock-In and Clock-Out Records Across Calendar Days

SQL & DataModel answer
MediumModel answerSQL & Datasqlwindow-functionstime-series

Last updated

Calculate daily hours worked per employee from timestamp-based clock events, handling midnight transitions and data anomalies.

You maintain a time-tracking system that records when employees clock in and out. Your task is to calculate how many hours each employee worked on each calendar day.

You have a table of clock events:

events(employee_id INT, evt_ts TIMESTAMP, action VARCHAR)

where action is either 'in' or 'out'.

Example data:

employee_id | evt_ts              | action
------------|---------------------|-------
101         | 2025-01-30 08:00:00 | in
101         | 2025-01-30 13:00:00 | out
101         | 2025-01-30 14:00:00 | in
101         | 2025-01-30 18:30:00 | out
102         | 2025-01-30 22:00:00 | in
102         | 2025-01-31 06:00:00 | out
103         | 2025-01-30 09:00:00 | in
103         | 2025-01-30 12:00:00 | out
103         | 2025-01-30 12:30:00 | out

Your solution must:

  1. Match each clock-in with its corresponding clock-out (the next 'out' event chronologically for that employee)
  2. Handle shifts that cross midnight by attributing hours to the correct calendar days
  3. Deal with incomplete or malformed data:
    • If a clock-in has no matching clock-out, count hours until 23:59:59 of that same day
    • Ignore clock-out events that have no preceding clock-in
  4. Round daily totals to the nearest quarter-hour (0.25)
  5. Mark days where anomalies occur (consecutive clock-ins, consecutive clock-outs, or duplicate timestamps)

Return a result set with columns:

  • employee_id
  • work_date (the calendar date)
  • hours_worked (rounded to nearest 0.25)
  • dq_issue_flag (boolean indicating data quality problems on that day)

Write a SQL query (PostgreSQL dialect) to produce this output.

Hints

Hint 1

Use window functions like LEAD and LAG to examine adjacent events for each employee without expensive self-joins

Hint 2

When a shift spans multiple days, generate one row per affected calendar day and clip the time interval to that day's boundaries

Hint 3

Round the summed daily total rather than rounding individual segments to avoid compounding rounding errors