Join signups to summarized order totals
Your task
For each signup source, return source, signup_count, total_orders across all statuses, and customers_with_orders. Include customers who placed no orders and sort by source.
Counting customer rows after an unaggregated join can count buyers multiple times.
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 | signup_count | total_orders | customers_with_orders |
|---|---|---|---|
| 3 | 5 | 3 | |
| organic | 3 | 4 | 3 |
| social | 2 | 1 | 1 |
Show a hint
Count orders per customer first. Then left join that summary to customers and aggregate by source.
Joins and set operations guide
Match rows by a key
A join combines columns horizontally. The condition links sales.album_id to albums.id. If an album has three sale records, a join can return its title three times.
SELECT s.id AS sale_id, a.title, s.quantity
FROM sales AS s
JOIN albums AS a ON a.id = s.album_id;Preserve rows without a match
A LEFT JOIN retains each album. The quantity condition belongs in ON because it defines which sales qualify as matches. Placing it in WHERE would also remove albums whose sale columns are NULL.
SELECT a.title, s.id AS large_sale_id
FROM albums AS a
LEFT JOIN sales AS s
ON s.album_id = a.id
AND s.quantity >= 3;Combine result sets vertically
UNION stacks compatible result sets and removes duplicate rows. UNION ALL keeps every row. INTERSECT keeps shared rows, and EXCEPT keeps rows unique to the first result. With set operations, both inputs must return the same number of columns.
SELECT title FROM albums WHERE genre = 'Jazz'
UNION
SELECT title FROM albums WHERE price < 20;Worked solution
WITH o AS (SELECT customer_id, COUNT(*) AS orders FROM shop_orders GROUP BY customer_id) SELECT c.source, COUNT(*) AS signup_count, COALESCE(SUM(o.orders),0) AS total_orders, COUNT(o.customer_id) AS customers_with_orders FROM customers c LEFT JOIN o ON o.customer_id=c.id GROUP BY c.source ORDER BY c.source;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
