Databases with SQLite · 8 / 15 Exercise Medium

Total per category

Objective

Create a Python program that groups sales by category with GROUP BY and the aggregate functions SUM and COUNT. Use an in-memory database with the sqlite3 module (sqlite3.connect(":memory:")).

Instructions

  • Create the table sales with category (text) and amount (integer).
  • Read n and then n lines with category amount and insert them.
  • With a single query get, per category, the sum of amounts and the number of sales. Sort by sum descending and, in case of a tie, by category.
  • Show each row as category: total (sales: k).
Input
5
fruta 10
carne 25
fruta 5
bebida 7
carne 3
Output
carne: 28 (sales: 2)
fruta: 15 (sales: 2)
bebida: 7 (sales: 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