Hours between scans

window functions

Hours between scans

Amazon SQL Interview Question

A package sitting four hours between being picked and being packed is a bottleneck at the pack bench. A package sitting four hours before it is picked is a bottleneck in the pick path. They need different fixes and different people, so the delay has to be attributed to the step it happened in.

Return the package_id, the stage scanned, the scanned_at time, and the hours since that package's previous scan as hours_since_previous, rounded to 2 decimal places. A package's first scan has nothing before it, so leave its gap empty. Sort by package_id and then by scanned_at.

Asked of

  • Data Analyst
  • Analytics Engineer
  • Data Engineer
  • Data Scientist

amazon_fulfillment_scansTable24 rows

Column NameType
scan_idBIGINT
package_idVARCHAR
facilityVARCHAR
scanned_atTIMESTAMP
stageVARCHAR

amazon_fulfillment_scansExample Input

scan_idpackage_idfacilityscanned_atstage
101P001BLR12024-11-01 09:05:00received
102P001BLR12024-11-01 10:20:00picked
103P001BLR12024-11-01 11:15:00packed
104P001BLR12024-11-01 13:40:00shipped
105P001BLR12024-11-02 09:30:00delivered
123P006HYD32024-11-01 07:50:00received
124P006HYD32024-11-01 09:40:00picked

Example Output

package_idstagescanned_athours_since_previous
P001received2024-11-01 09:05:00NULL
P001picked2024-11-01 10:20:001.25
P001packed2024-11-01 11:15:000.92
P001shipped2024-11-01 13:40:002.42
P001delivered2024-11-02 09:30:0019.83
P006received2024-11-01 07:50:00NULL
P006picked2024-11-01 09:40:001.83

Explanation

P001's first scan has nothing before it, so its gap is empty. It was picked 1.25 hours later, packed 0.92 hours after that, and shipped 2.42 hours after packing. The delivery scan is 19.83 hours later, most of that overnight.

The example above is a small slice of the data. Your query runs against the full tables.