Measure purchase conversion after a first product view
Your task
For each signup source with at least one product viewer, return source, viewers, converted_viewers, and conversion_pct. A viewer converts if they purchase after their first view and before seven days from that view. Compare timestamp then event ID for the lower bound. Round the percentage to one decimal and sort by source.
A customer-level conversion can span several sessions. Each viewer should contribute at most once to each count.
Sample data
| id | name | signup_date | source |
|---|---|---|---|
| 1 | Avery | 2025-01-02 | organic |
| 2 | Casey | 2025-01-05 | |
| 3 | Jordan | 2025-01-12 | organic |
| 4 | Morgan | 2025-02-01 | |
| 5 | Riley | 2025-02-10 | social |
| 6 | Sam | 2025-02-20 | organic |
| 7 | Taylor | 2025-03-01 | social |
| 8 | Devon | 2025-02-07 |
Expected output
| source | viewers | converted_viewers | conversion_pct |
|---|---|---|---|
| 3 | 3 | 100 | |
| organic | 3 | 1 | 33.3 |
| social | 1 | 0 | 0 |
Show a hint
Rank product views per customer, then test for a qualifying purchase with EXISTS before aggregating by source.
Product events and funnels guide
Choose the event, session, or customer grain
An event is one logged action. A session is a group of events with the same session_key. A customer can have several sessions. Choose the grain before counting so a busy visitor cannot accidentally count as many people.
SELECT event_name, COUNT(*) AS events, COUNT(DISTINCT session_key) AS sessions
FROM product_events
GROUP BY event_name
ORDER BY event_name;Order events before evaluating a funnel
A funnel measures steps completed in a defined order. Events in the same session can share an exact timestamp, so use the event ID as a tie-breaker. A session with a purchase before the cart event does not meet a view, cart, purchase funnel.
SELECT session_key, event_name,
ROW_NUMBER() OVER (PARTITION BY session_key ORDER BY event_at, id) AS position
FROM product_events
ORDER BY session_key, position;Worked solution
WITH views AS (SELECT customer_id,event_at,id,ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY event_at,id) AS pos FROM product_events WHERE event_name='view_product'), flags AS (SELECT c.source,EXISTS (SELECT 1 FROM product_events p WHERE p.customer_id=v.customer_id AND p.event_name='purchase' AND (p.event_at,p.id)>(v.event_at,v.id) AND p.event_at<DATETIME(v.event_at,'+7 days')) AS converted FROM views v JOIN customers c ON c.id=v.customer_id WHERE v.pos=1) SELECT source,COUNT(*) AS viewers,SUM(converted) AS converted_viewers,ROUND(100.0*SUM(converted)/COUNT(*),1) AS conversion_pct FROM flags GROUP BY source ORDER BY source;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
