I have four tables: supplier, products, sales and sale_products. The suppliers and products table are associated in a one-to-many relationship, whereby a supplier can own multiple products and a product belongs to a single supplier. The products and sales tables are joined in a many-to-many relationship with the sale_products table acting as an intermediate table that connects the products and sales table.
Sample structure of the tables:
1. suppliers
+----+--------------------+
| id | name |
+----+--------------------+
| 1 | Sup A |
| 2 | Sup B |
| 3 | Cus A |
| 4 | Cus B |
| 5 | Sky Song Fireworks |
+----+--------------------+
2. products
+----+--------------------+-------------+
| id | name | supplier_id |
+----+--------------------+-------------+
| 1 | Pop Pops | 6 |
| 2 | Pop Pops | 5 |
| 3 | Color Pop Pop Snap | 5 |
| 4 | Rubbing Bang | 5 |
| 5 | Kids Bag | 5 |
+----+--------------------+-------------+
3. sales
+----+-----------------+-----------------------+
| id | discount_amount | receipt |
+----+-----------------+-----------------------+
| 4 | NULL | RCT-19-10-12-04/06/51 |
| 5 | 2000 | RCT-19-10-14-07/36/58 |
| 6 | NULL | RCT-19-10-14-07/40/28 |
| 7 | NULL | RCT-19-10-15-12/10/20 |
| 8 | 2000 | RCT-19-10-15-12/14/51 |
+----+-----------------+-----------------------+
4. sale_products
+----+------------+---------+----------+------------+
| id | product_id | sale_id | quantity | unit_price |
+----+------------+---------+----------+------------+
| 1 | 335 | 1 | 4 | 150 |
| 2 | 336 | 2 | 4 | 1000 |
| 3 | 335 | 3 | 5 | 150 |
| 4 | 445 | 4 | 5 | 150 |
| 5 | 564 | 5 | 100 | 200 |
+----+------------+---------+----------+------------+
I want to run a query that gets the total discount from sales table for each supplier whose product was part of a sale. The query could give a result as follows:
+----+--------------------+----------------+
| id | name | total_discount |
+----+--------------------+----------------+
| 1 | Sup A | 1000 |
| 2 | Sup B | 200 |
+----+--------------------+----------------+