Reputation: 111
I need to generate a report like the below table
Collection |Model|Units Sold|Price USD |Price Euro|Price gbp
-----------------+-----+----------+----------+----------+----------
Pays de la Loire | 1301| 2| 1000| 600| 400
Toscana | 1301| 1| 500| 300| 200
Provence | 1302| 1| 400| 400| 400
Below are the 3 tables from where this above i need to generate
order Table
ID|collection_fk|model_fk
--+-----------+---------
1| 1| 1
2| 1| 1
3| 2| 1
4| 3| 2
Collection Table
ID|Collection
--+-----------
1| Pays de la Loire
2| Toscana
3| Provence
4| Lorraine
Models Table
ID|model_no |collection_fk|price_usd|price_euro|price_gbp
--+-----------+-------------+---------+----------+---------
1| 1301| 1| 500| 300| 200
2| 1302| 1| 400| 400| 400
3| 1303| 2| 300| 200| 500
4| 1304| 3| 200| 100| 300
How would i write a query to get sum of same collection and models and count number of units sold an count their price accordingly.
Upvotes: 0
Views: 5290
Reputation: 64476
Use joins with some aggregation
select
c.Collection,
m.model_no,
count(o.ID) units_sold,
sum(m.price_usd),
sum(m.price_euro),
sum(m.price_gbp)
from model m
join `order` o on m.ID = o.model_fk
join collection c on c.ID = o.collection_fk
group by c.Collection,m.model_no
order by m.model_no
Upvotes: 2