mardi 1 septembre 2015

SQLite Relational Database Query in Ruby

I have 2 SQLite databases, Salesmen and Sales. Here's what the original CSV files looked like, but I've already put them in SQLite (just so you can see how the tables are layed out):

Salesmen Table
id, name
1, john
2, luther
3, bob

Sales Table
id, salesmen_id, sales_amount
1, 1, 100
2, 3, 20
3, 2, 35
4, 3, 25
5, 1, 55
6, 2, 200
7, 2, 150

My question is how do I write a function in ruby that will return all the Salesmen names, sorted by their total sales amount? I know this requires using a join, but I'm not entirely sure how the query should look like.

I want the new table to look like this:

New Table
name, total_sales
luther, 385
john, 155
bob, 45

The new sqlite query should be in this format:

$db.execute %q{
    SELECT account_name, units, unit_price 
    FROM accounts, positions
    ...
}

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire