Join orders to customers: return each city with total order amount and number of orders. Table definitions (from the…
SQLLevel: IntermediateAggregation and HAVING
Join orders to customers: return each city with total order amount and number of orders.
Table definitions (from the source exercise):
CREATE TABLE customers(customer_id INTEGER PRIMARY KEY, name TEXT, city TEXT, signup_date TEXT, credit_score INTEGER);
CREATE TABLE orders(order_id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, amount REAL, rep_id INTEGER, discount REAL);
Hints
- Write the join keys and relationship cardinality.
- What happens to duplicates and unmatched rows? Check WHERE versus ON.
Answer
Approach: Two aggregates after one join, grouped by city.
SELECT c.city, SUM(o.amount) AS revenue, COUNT(*) AS num_orders
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
GROUP BY c.city;
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT