Measure repeat buyers by signup source
Your task
For each signup source, return customer_count, repeat_buyers, and repeat_pct. Return the percentage on a 0–100 scale, rounded to one decimal place. Sort by source alphabetically.
A repeat buyer has at least two completed orders. The denominator for this report includes everyone who signed up, even customers who never bought anything.
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 | customer_count | repeat_buyers | repeat_pct |
|---|---|---|---|
| 3 | 2 | 66.7 | |
| organic | 3 | 1 | 33.3 |
| social | 2 | 0 | 0 |
Show a hint
First count completed orders per customer with a LEFT JOIN. Then group those customer-level rows by source, counting a repeat buyer when the order count is at least two.
Customer and sales analytics guide
Define which orders count
This part of the record shop database tracks customer orders separately from the earlier album sales table. A completed order contributes its full price in cents. Refunded orders are fully refunded, and cancelled orders contribute zero. Decide whether you need to keep all statuses for a report or count only completed orders.
SELECT status, COUNT(*) AS orders
FROM shop_orders
GROUP BY status
ORDER BY status;Group at the customer level first
A customer can have several orders. Summarize by customer ID before counting customers or averaging customer-level values. To include customers with no completed orders, start with customers and put the completion filter in the LEFT JOIN condition.
SELECT c.id, COUNT(o.id) AS completed_orders
FROM customers AS c
LEFT JOIN shop_orders AS o
ON o.customer_id = c.id AND o.status = 'completed'
GROUP BY c.id
ORDER BY c.id;Choose a date boundary
Order and signup dates are stored as YYYY-MM-DD. A half-open date range includes its start and excludes its end. The example counts January orders by including January 1 and stopping before February 1.
SELECT COUNT(*) AS january_orders
FROM shop_orders
WHERE ordered_on >= '2025-01-01' AND ordered_on < '2025-02-01';Worked solution
WITH per_customer AS (
SELECT c.id, c.source, COUNT(o.id) AS completed_orders
FROM customers AS c
LEFT JOIN shop_orders AS o ON o.customer_id = c.id AND o.status = 'completed'
GROUP BY c.id, c.source
)
SELECT source, COUNT(*) AS customer_count,
SUM(CASE WHEN completed_orders >= 2 THEN 1 ELSE 0 END) AS repeat_buyers,
ROUND(100.0 * SUM(CASE WHEN completed_orders >= 2 THEN 1 ELSE 0 END) / COUNT(*), 1) AS repeat_pct
FROM per_customer
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…
