cswork / libraryOpen practice workspace

Coding questions · Agoda

Sum Employee Working Time from Ordered Check-In and Check-Out Events

Pair ordered employee attendance events and total working seconds, including multiple shifts and intervals crossing midnight.

Compute each employee's total working duration by pairing every check-out event with that employee's immediately preceding check-in event.

Input Table

attendance_events

ColumnTypeMeaning
event_idINTEGERPrimary key
employee_idINTEGERNon-null employee identifier
event_timeTIMESTAMPNon-null timestamp with whole-second precision
event_typeTEXTEither in or out

Output Contract

Write one read-only PostgreSQL query returning employee_id and total_seconds, one row per employee present in the table, ordered by employee_id ascending. Sum elapsed seconds for all that employee's completed check-in/check-out pairs.

Constraints and Clarifications

To make the pairing unambiguous, this exercise guarantees that each employee's events, ordered by (event_time, event_id), alternate in, out, start with in, and finish with out. There are no unmatched events. Equal timestamps are allowed and can create a zero-duration pair. A work interval may cross midnight; subtract full timestamps rather than time-of-day values.

Example

event_idemployee_idevent_timeevent_type
1102026-01-01 09:00:00in
2102026-01-01 10:00:00out
3102026-01-01 10:30:00in
4102026-01-01 11:00:00out
5202026-01-01 23:30:00in
6202026-01-02 00:30:00out

Expected result:

employee_idtotal_seconds
105400
203600

Hint: Keep both event types while finding neighbors

The preceding check-in must still be present when you calculate the previous timestamp for a check-out. Filtering too early can make the previous row another check-out instead.

Total Working Duration from Check-In/Check-Out Events

Table attendance_events

columntypeconstraints
event_idINTEGERPRIMARY KEY
employee_idINTEGERNOT NULL
event_timeTIMESTAMPNOT NULL
event_typeTEXT

Sample data:

employee_idevent_idevent_timeevent_type
1012026-03-02 08:55:00in
3022026-03-02 09:00:00in
2032026-03-03 06:30:00out
1042026-03-02 12:05:30out
2052026-03-02 14:00:00in
2062026-03-02 18:00:00out
1072026-03-02 13:00:00in
3082026-03-02 09:00:00out
1092026-03-02 17:45:15out
30102026-03-02 09:00:00in
30112026-03-02 11:00:00out
20122026-03-02 22:00:00in

Expected output

employee_idtotal_seconds
1028545
2045000
307200

Hints

  1. Keep both event types while finding neighbors: the preceding check-in must still be present when you calculate the previous timestamp for a check-out. Filtering too early can make the previous row another check-out instead.