Marketing permissions per non-purchaser, across 9 sites.
Email permissions + SMS permissions. A user with both contributes 2. Each channel is counted independently because each is an independent way to reach the user.
Users where customer = FALSE OR customer IS NULL. NULL is treated as a non-purchaser to cover anonymous and unconverted visitors.
SAFE_DIVIDE(numerator, denominator) — returns NULL instead of erroring on a zero denominator (e.g. a brand-new site with no non-purchasers yet).
email on file (otherwise there's nothing to send to).email_consented = TRUE — opted in.email_consented = FALSE AND email_consented_updated_at IS NULL — never explicitly opted out (default state, not a real "no").email_consented = FALSE with a timestamp — active unsubscribe, excluded.phone on file.sms_consented = TRUE — explicit opt-in required.-- Single-site exchange rate. website_id is the primary key, -- so this is a fast point lookup. Cross-site = full scan = expensive. SELECT COUNTIF( email IS NOT NULL AND ( email_consented = TRUE OR (email_consented = FALSE AND email_consented_updated_at IS NULL) ) ) AS email_permissions, COUNTIF(phone IS NOT NULL AND sms_consented = TRUE) AS sms_permissions, COUNTIF(/* email rule */) + COUNTIF(/* sms rule */) AS total_permissions, COUNTIF(customer = TRUE) AS purchasers, COUNTIF(customer = FALSE OR customer IS NULL) AS non_purchasers, SAFE_DIVIDE( COUNTIF(/* email rule */) + COUNTIF(/* sms rule */), COUNTIF(customer = FALSE OR customer IS NULL) ) AS exchange_rate FROM `user` WHERE website_id = 'NaVnjma'; -- Final Boss Sour