Databases with SQLite · 13 / 15 Exercise Hard

Customers and orders

Objective

Create a Python program that relates two tables with LEFT JOIN and computes each customer's total, even if they have no orders. Use an in-memory database with the sqlite3 module (sqlite3.connect(":memory:")).

Instructions

  • Create customers (id integer primary key, name text) and orders (customer_id and amount integers).
  • Read n customer names (one per line): their id will be 1, 2, 3... in insertion order (generated automatically).
  • Read m and then m lines with index amount, where index is the position of the customer (1 is the first). Insert each order.
  • With LEFT JOIN and GROUP BY get, per customer, the sum of amounts (COALESCE so that it is 0 when there are no orders) and the number of orders. Sort by name and show name: total (orders: k).
Input
3
ana
bea
carlos
4
1 10
1 20
3 5
1 1
Output
ana: 31 (orders: 3)
bea: 0 (orders: 0)
carlos: 5 (orders: 1)

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise