WITH LeadAssignments AS (
-- Find the first time each lead was assigned
SELECT
customer_id,
ts AS assigned_ts
FROM customer_stream
WHERE activity = 'lead_assigned'
QUALIFY ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY ts ASC) = 1
),
FirstTouch AS (
-- Find the first sales touch after assignment
SELECT
la.customer_id,
MIN(cs.ts) AS first_touch_ts
FROM LeadAssignments la
JOIN customer_stream cs ON la.customer_id = cs.customer_id
WHERE
cs.activity IN ('call', 'email')
AND cs.ts >= la.assigned_ts
GROUP BY 1
),
LeadResponseTime AS (
-- Calculate time to first touch in hours
SELECT
la.customer_id,
DATEDIFF('hour', la.assigned_ts, ft.first_touch_ts) AS time_to_first_touch_hours
FROM LeadAssignments la
LEFT JOIN FirstTouch ft ON la.customer_id = ft.customer_id
),
Conversions AS (
-- Identify which customers converted
SELECT DISTINCT customer_id
FROM customer_stream
WHERE activity = 'created_subscription'
),
BinnedLeads AS (
SELECT
lrt.customer_id,
CASE
WHEN lrt.time_to_first_touch_hours < 1 THEN 'Within 1 Hour'
WHEN lrt.time_to_first_touch_hours < 24 THEN '1-24 Hours'
WHEN lrt.time_to_first_touch_hours < 72 THEN '1-3 Days'
WHEN lrt.time_to_first_touch_hours < 168 THEN '3-7 Days'
ELSE '7+ Days or No Touch'
END AS time_to_touch_bucket
FROM LeadResponseTime lrt
)
SELECT
bl.time_to_touch_bucket,
COUNT(DISTINCT bl.customer_id) AS total_leads,
COUNT(DISTINCT c.customer_id) AS total_wins,
(COUNT(DISTINCT c.customer_id) * 1.0 / COUNT(DISTINCT bl.customer_id)) AS win_rate
FROM BinnedLeads bl
LEFT JOIN Conversions c ON bl.customer_id = c.customer_id
GROUP BY 1
ORDER BY
CASE bl.time_to_touch_bucket
WHEN 'Within 1 Hour' THEN 1
WHEN '1-24 Hours' THEN 2
WHEN '1-3 Days' THEN 3
WHEN '3-7 Days' THEN 4
ELSE 5
END;