← Problems17. First-touch attributionMediumSQL
00:00 / 20:00

First-touch attribution

MediumNot attempted yetAsked at Uber, Swiggy, Google

For every conversion, return the first marketing touch by the same user within the 30 days before it. Conversions with no touch in that window still appear, with a null channel and touched_at.

Input schema

touches conversions user_id bigint conversion_id bigint channel varchar user_id bigint touched_at timestamp converted_at timestamp

Output

conversion_id, user_id, channel, touched_at — one row per conversion.

Constraints

  • The window is converted_at - 30 days <= touched_at <= converted_at, both ends inclusive. A touch after the conversion does not count.
  • Ties on touched_at break on channel ascending.
  • Order by conversion_id.
  • touches has up to 200,000,000 rows, so a correlated subquery per conversion will time out.

Example 1Example

Input · touches
channeluser_idtouched_at
email422024-04-03 18:00:00
search422024-04-01 09:00:00
display432024-01-01 00:00:00
Input · conversions
user_idconverted_atconversion_id
422024-04-10 12:00:00900
432024-04-10 12:00:00901
Output
conversion_iduser_idchanneltouched_at
90042search2024-04-01 09:00:00
90143nullnull

Example 2Window boundaries

Input · touches
channeluser_idtouched_at
display12024-03-01 11:59:59
search12024-03-01 12:00:00
email12024-03-31 12:00:01
social22024-03-31 12:00:00
Input · conversions
user_idconverted_atconversion_id
12024-03-31 12:00:0010
22024-03-31 12:00:0011
Output
conversion_iduser_idchanneltouched_at
101search2024-03-01 12:00:00
112social2024-03-31 12:00:00

Topics

window functionsjoinsattribution

Similar problems

Community-reported interview topic. Not an official company question and no affiliation is implied.

solution.sql
Loading editor…
Draft not saved yet · Spaces 4 · UTF-8⌘↵ run ⌘⇧↵ submit
Nothing run yet

Run against the public tests, or submit to score against all of them.