Point-in-Time User Features and 30-Day Purchase Label in SQL
SQL & DataModel answerLast updated
Build a leakage-free training table at a fixed snapshot: deduplicated, arrival-aware 7-day activity features per user, plus a forward-looking 30-day purchase label.
You are preparing a training set for a purchase-prediction model. The set must be built as of a fixed moment, so that every feature reflects only what the system could have known then, and the label looks only forward.
Take snapshot_ts = '2025-09-01 00:00:00' (UTC). The schema is:
users(u_id INT, signup_dt DATE, country STRING)
events(u_id INT, event_time TIMESTAMP, arrival_time TIMESTAMP, event_type STRING, session_id STRING)
orders(order_id INT, u_id INT, order_time TIMESTAMP, amount DECIMAL(10,2))
event_time is when the action happened. arrival_time is when the row landed in the warehouse.
users
| u_id | signup_dt | country |
|---|---|---|
| 1 | 2025-07-20 | US |
| 2 | 2025-08-25 | CA |
| 3 | 2025-08-30 | US |
events
| u_id | event_time | arrival_time | event_type | session_id | note |
|---|---|---|---|---|---|
| 1 | 2025-08-29 10:00:00 | 2025-08-29 10:00:02 | view | a | |
| 1 | 2025-08-31 09:00:00 | 2025-08-31 09:00:03 | add_to_cart | a | |
| 1 | 2025-09-01 12:00:00 | 2025-09-01 12:00:01 | view | b | |
| 2 | 2025-08-30 15:00:00 | 2025-08-30 15:00:02 | view | c | |
| 2 | 2025-09-01 09:30:00 | 2025-09-01 09:30:01 | view | d | |
| 3 | 2025-08-31 23:59:00 | 2025-09-02 00:00:05 | view | e | late-arriving |
| 3 | 2025-09-01 08:00:00 | 2025-09-01 08:00:00 | view | e | |
| 3 | 2025-09-01 08:00:00 | 2025-09-01 08:00:00 | view | e | exact duplicate |
orders
| order_id | u_id | order_time | amount |
|---|---|---|---|
| 101 | 1 | 2025-09-10 13:00:00 | 120.00 |
| 102 | 2 | 2025-08-31 16:00:00 | 50.00 |
| 103 | 2 | 2025-09-03 11:00:00 | 60.00 |
Task. Write a single SQL query returning one row per user with these columns:
u_id, country, days_since_signup, last_event_time, events_7d, sessions_7d, added_to_cart_7d, y_30d
Rules:
- Visibility and dedup. Features may use only events with
event_time < snapshot_tsANDarrival_time <= snapshot_ts. Drop duplicates on(u_id, event_time, event_type, session_id). - Window. The 7-day window is
[snapshot_ts - 7 days, snapshot_ts). - Counts.
sessions_7dis the number of distinctsession_idvalues in the window.events_7dis the number of distinct(event_time, event_type, session_id)combinations in the window. - Label.
y_30d = 1if the user has at least one order in[snapshot_ts, snapshot_ts + 30 days), otherwise0. - Users without events. They must still appear, with zeros or NULLs filled in sensibly.
Also:
- Show the exact output rows for the sample data.
- Explain why user 3's late-arriving 2025-08-31 event must not contribute to the features.
Hints
Hint 1
Start from the user table as the driving set and LEFT JOIN pre-aggregated feature and label subqueries, so users with no activity are not lost and joins do not fan out.
Hint 2
Apply the visibility filter (event_time < snapshot and arrival_time <= snapshot) and de-duplicate first. Then compute last_event_time over all visible rows, and the 7-day counts with conditional aggregation restricted to the window.
Hint 3
Reduce orders to one row per user (the label window is forward-looking and half-open) before joining. Use COALESCE for counts and the label, but leave last_event_time as NULL when nothing is visible.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
This is a point-in-time correctness problem. A feature may use only what the system knew at snapshot_ts, and the label may use only what happens after it. Two clocks matter: event_time (when it happened) and arrival_time (when we learned about it). Only the combination of both gives a faithful snapshot.
Approach
- Population. Take users with
signup_dt < snapshot date. This table drives the query, so every user gets exactly one row. - Visible events. Filter on
event_time < snapshot_ts AND arrival_time <= snapshot_ts, thenSELECT DISTINCTon(u_id, event_time, event_type, session_id). - Feature aggregation per user.
last_event_timeis the max over all visible history.events_7d,sessions_7dandadded_to_cart_7duse conditional aggregation onevent_time >= snapshot_ts - 7 days. The upper bound is already enforced by the visibility filter.
- Label. Aggregate orders in
[snapshot_ts, snapshot_ts + 30 days)to one row per user. - Assemble. LEFT JOIN features and labels onto the population, then
COALESCEcounts and label to 0.
Query (Trino/ANSI style)
WITH params AS (
SELECT TIMESTAMP '2025-09-01 00:00:00' AS snapshot_ts
),
population AS (
SELECT u.u_id, u.country, u.signup_dt
FROM users u CROSS JOIN params p
WHERE u.signup_dt < CAST(p.snapshot_ts AS DATE)
),
visible_events AS (
SELECT DISTINCT e.u_id, e.event_time, e.event_type, e.session_id
FROM events e CROSS JOIN params p
WHERE e.event_time < p.snapshot_ts
AND e.arrival_time <= p.snapshot_ts
),
event_feats AS (
SELECT
v.u_id,
MAX(v.event_time) AS last_event_time,
COUNT(CASE WHEN v.event_time >= p.snapshot_ts - INTERVAL '7' DAY
THEN 1 END) AS events_7d,
COUNT(DISTINCT CASE WHEN v.event_time >= p.snapshot_ts - INTERVAL '7' DAY
THEN v.session_id END) AS sessions_7d,
MAX(CASE WHEN v.event_time >= p.snapshot_ts - INTERVAL '7' DAY
AND v.event_type = 'add_to_cart'
THEN 1 ELSE 0 END) AS added_to_cart_7d
FROM visible_events v CROSS JOIN params p
GROUP BY v.u_id
),
labels AS (
SELECT o.u_id, 1 AS y_30d
FROM orders o CROSS JOIN params p
WHERE o.order_time >= p.snapshot_ts
AND o.order_time < p.snapshot_ts + INTERVAL '30' DAY
GROUP BY o.u_id
)
SELECT
pop.u_id,
pop.country,
DATE_DIFF('day', pop.signup_dt, CAST(p.snapshot_ts AS DATE)) AS days_since_signup,
ef.last_event_time,
COALESCE(ef.events_7d, 0) AS events_7d,
COALESCE(ef.sessions_7d, 0) AS sessions_7d,
COALESCE(ef.added_to_cart_7d, 0) AS added_to_cart_7d,
COALESCE(l.y_30d, 0) AS y_30d
FROM population pop
CROSS JOIN params p
LEFT JOIN event_feats ef ON ef.u_id = pop.u_id
LEFT JOIN labels l ON l.u_id = pop.u_id
ORDER BY pop.u_id;
Notes:
- Because rows are already distinct, counting rows in the window equals counting distinct
(event_time, event_type, session_id). This also avoids multi-columnCOUNT(DISTINCT ...), which is not portable. added_to_cart_7dis a 0/1 flag here. If a count is wanted, useCOUNT(CASE WHEN ... THEN 1 END). The sample output is the same either way.- Date difference is dialect-specific: Postgres
DATE '2025-09-01' - signup_dt, SparkDATEDIFF(end, start), BigQueryDATE_DIFF(end, start, DAY).
Expected output
The 7-day window is [2025-08-25 00:00:00, 2025-09-01 00:00:00).
| u_id | country | days_since_signup | last_event_time | events_7d | sessions_7d | added_to_cart_7d | y_30d |
|---|---|---|---|---|---|---|---|
| 1 | US | 43 | 2025-08-31 09:00:00 | 2 | 1 | 1 | 1 |
| 2 | CA | 7 | 2025-08-30 15:00:00 | 1 | 1 | 0 | 1 |
| 3 | US | 2 | NULL | 0 | 0 | 0 | 0 |
Walk-through:
- User 1. The 08-29 view and the 08-31 add_to_cart are visible, both in session
a. The 09-01 12:00 event lies after the snapshot and is excluded. Order 101 (09-10) falls inside the label window, soy_30d = 1. - User 2. Only the 08-30 view is visible. The 09-01 09:30 event is in the future. Order 102 (08-31) is before the snapshot, so it is past behavior and cannot be a label. Order 103 (09-03) is inside the window, so
y_30d = 1. - User 3. The 08-31 23:59 event arrived on 09-02, so it fails the arrival filter. The two 09-01 08:00 rows (an exact duplicate pair) fail
event_time < snapshot_ts. Nothing is visible, so the counts are 0 andlast_event_timeis NULL. There are no orders, soy_30d = 0.
Why the late-arriving event must be excluded
The event occurred before the snapshot, but the system did not know about it until 2025-09-02. A model scoring user 3 at 2025-09-01 00:00 in production would have seen no events at all. Including it in training would give user 3 events_7d = 1, sessions_7d = 1 and a last_event_time of 08-31 23:59. That causes:
- Leakage. The features use information unavailable at decision time.
- Training/serving skew. Training data looks fresher and denser than what the model sees online, so offline metrics overstate real performance.
Filtering on arrival_time (bitemporal, "as-of" logic) makes the training row identical to what the online feature store would have returned.
Why it is correct
- Population drives the query, so no user is lost (rule 5).
- No join fan-out. Features and labels are each one row per user before joining. A raw join to
orderswould duplicate rows for multi-order users. - Half-open intervals (
>= start AND < end) prevent double counting at boundaries between consecutive snapshots. - Dedup after the visibility filter operates on exactly the data the feature store would hold.
- Deliberate NULLs. Counts become 0 because no activity really is zero.
last_event_timestays NULL because no timestamp exists. Downstream, derivedays_since_last_eventwith a sentinel plus a missing-indicator.
Complexity
With E events, O orders and U users, time is roughly O(E + O + U): one filtered scan per table plus hash-based dedup and aggregation. Space is O(visible distinct events + U). At scale, partition events by date so the scan prunes. Since last_event_time spans all history, maintain it incrementally instead of rescanning.
Common mistakes
- Filtering only on
event_timeand forgettingarrival_time. - Starting from
eventsand an inner join, which drops users with no activity. - Joining
ordersdirectly and inflating rows. - Using
<=on the window end, which pulls in snapshot-instant events. - Counting duplicates, or deduplicating before the visibility filter.
- Replacing a missing
last_event_timewith 0 or a fake date without a missing flag. - Including users who signed up on or after the snapshot date.