简体   繁体   中英

How to write a SQL query to generate a report in mysql

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.

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

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM