KatInterview

Reconstruct the Latest State of Every Listing

SQL & DataModel answer
HardModel answerSQL & Datawindow-functionsaggregationtimestamp-arithmetic

Last updated

Query an event-log table to produce one row per listing showing its most recent status and total lifespan in hours.

Background

A marketplace platform records every status change for its listings in an event log. Each row captures a single transition — nothing is ever updated in place. To answer business questions you need to reconstruct the current state of every listing from that history.

Table: listing_events

ColumnTypeDescription
event_idINTUnique identifier for this log entry
listing_idINTThe listing this event belongs to
statusVARCHARNew status after the transition (e.g. 'ACTIVE', 'PENDING', 'SOLD', 'WITHDRAWN')
occurred_atTIMESTAMPWhen the transition happened

Your Task

Write a SQL query that returns one row per listing with three columns:

ColumnDefinition
listing_idThe listing identifier
current_statusThe status from the most recent event for that listing
lifespan_hoursElapsed hours between the listing's very first and very last event; 0.0 for listings with only one event

Order the results by listing_id ascending.

Example

Input

event_idlisting_idstatusoccurred_at
1201ACTIVE2024-03-01 08:00:00
2201PENDING2024-03-01 11:30:00
3201SOLD2024-03-02 08:00:00
4202ACTIVE2024-03-01 09:00:00

Expected Output

listing_idcurrent_statuslifespan_hours
201SOLD24.0
202ACTIVE0.0

Constraints

  • listing_id values repeat across rows (one listing has many events).
  • occurred_at is strictly increasing within a single listing — no two events for the same listing share the same timestamp.
  • Every row in the table belongs to a listing with at least one event.
  • Return lifespan_hours as a decimal, not truncated to an integer (3.5, not 3).

Hints

Hint 1

The most recent status is not MAX(status) — that gives the alphabetically last value, not the chronologically last one. You need the status that belongs to the row with the latest occurred_at.

Hint 2

ROW_NUMBER() OVER (PARTITION BY listing_id ORDER BY occurred_at DESC) lets you tag the latest event as rn = 1. On that row, occurred_at is already the maximum, so you don't need a separate MAX pass — attach MIN(occurred_at) as a window function on the same partition and subtract.

Hint 3

Watch out for integer division when converting seconds to hours. Divide by 3600.0 (a float literal), not 3600, or a 90-minute lifespan silently becomes 1 instead of 1.5.