Business Analytics · Problem 94 of 118

Customer Funnel

MediumBusiness AnalyticsShop data

Return one row with four numbers: registered (all customers), ordered (customers with at least one order), delivered (customers with at least one order whose status is 'delivered') and reviewed (customers who wrote at least one review).

Hint 1

Count customers with a condition EXISTS (SELECT 1 FROM ... WHERE ... = c.customer_id) for each stage.

Reference solution

SELECT COUNT(*) AS registered,
       SUM(CASE WHEN EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id) THEN 1 ELSE 0 END) AS ordered,
       SUM(CASE WHEN EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id AND o.status = 'delivered') THEN 1 ELSE 0 END) AS delivered,
       SUM(CASE WHEN EXISTS (SELECT 1 FROM reviews AS r WHERE r.customer_id = c.customer_id) THEN 1 ELSE 0 END) AS reviewed
FROM customers AS c;

A funnel counts entities (customers) at each stage, not events. Counting orders or reviews makes the funnel grow instead of shrink, which is the giveaway that you counted the wrong thing. Each stage is a stricter condition on the same population, so the numbers should go down or stay equal; use that as a sanity check.

Another way. Four independent scalar subqueries, one per stage.

SELECT (SELECT COUNT(*) FROM customers) AS registered,
       (SELECT COUNT(DISTINCT customer_id) FROM orders) AS ordered,
       (SELECT COUNT(DISTINCT customer_id) FROM orders WHERE status = 'delivered') AS delivered,
       (SELECT COUNT(DISTINCT customer_id) FROM reviews) AS reviewed;