WITH Deals AS (
SELECT
customer_id,
ts AS assignment_ts
FROM customer_stream
WHERE activity = 'sdr_assigned'
QUALIFY ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY ts ASC) = 1
),
DealStats AS (
SELECT
d.customer_id,
SUM(CASE WHEN s.activity = 'email' THEN 1 ELSE 0 END) AS email_count,
MAX(CASE WHEN s.activity = 'closed_won' THEN 1 ELSE 0 END) AS is_won
FROM customer_stream s
JOIN Deals d ON s.customer_id = d.customer_id AND s.ts >= d.assignment_ts
GROUP BY d.customer_id
)
SELECT
CASE
WHEN email_count <= 2 THEN '0-2 Emails'
WHEN email_count <= 5 THEN '3-5 Emails'
WHEN email_count <= 10 THEN '6-10 Emails'
WHEN email_count <= 20 THEN '11-20 Emails'
ELSE '21+ Emails'
END AS email_bucket,
COUNT(distinct customer_id) AS total_deals,
SUM(is_won) AS won_deals,
(SUM(is_won) * 1.0 / COUNT(distinct customer_id)) AS win_rate
FROM DealStats
GROUP BY 1
ORDER BY MIN(email_count);