I have 4 tables :
Products - to record products
spending - to record expenses
directv - to record subscription payments to TV channels
sales - to record sales
Products has 4 columns : idProd
is the primary key
+--------+-----------+--------------+-------------+
| idProd | nameProd | sellingPrice | buyingPrice |
+--------+-----------+--------------+-------------+
| 1 | Iphone 8 | 500 | 400 |
| 2 | Samsung 2 | 600 | 400 |
+--------+-----------+--------------+-------------+
Spending - 3 columns and idSpd
is the primary key
+-------+--------+------------+
| idSpd | amount | dateSpd |
+-------+--------+------------+
| 1 | 1000 | 2018-11-01 |
| 2 | 1000 | 2018-11-01 |
| 3 | 1000 | 2018-10-01 |
| 4 | 4000 | 2018-10-01 |
+-------+--------+------------+
Sales - 5 columns with idSale
as primary key and idProd
to link it to the product's table
+--------+--------+--------------+----------+------------+
| idSale | idProd | sellingPrice | quantity | dateSale |
+--------+--------+--------------+----------+------------+
| 1 | 1 | 700 | 2 | 2018-11-01 |
| 2 | 1 | 700 | 5 | 2018-11-15 |
| 3 | 2 | 800 | 2 | 2018-11-16 |
+--------+--------+--------------+----------+------------+
and directv :
+-------+-----------------+-------+------------+
| idDtv | brand | price | dateDtv |
+-------+-----------------+-------+------------+
| 1 | channel decoder | 150 | 2018-11-09 |
+-------+-----------------+-------+------------+
and I wish to get for example :
income|gain of product | turnover | Spending | DirecTv | month | year
1000 | 400 | 5500 | 3000 | 50 | 10 |2018
500 | 200 | 1000 | 2000 | 0 | 11 |2018
my queries :
--for directv
select sum(dv.price) , month(dv.dateDtv), year(dv.dateDtv) from directv dv GROUP by year(dv.dateDtv) , month(dv.dateDtv)
--for turnover
select sum(sl.quantity*sl.sellingPrice) , month(sl.dateSale) , year(sl.dateSale) from sales sl GROUP by year(sl.dateSale) , month(sl.dateSale)
--for spending
select sum(spd.amount) , month(spd.dateSpd) , year(spd.dateSpd) from spending spd GROUP by year(spd.dateSpd) , month(spd.dateSpd)
--for gain of product
SELECT sum(s.quantity*(s.sellingPrice-p.buyingPrice)) from sales s JOIN products p on s.idProd = p.idProd GROUP by year(s.dateSale) , month(s.dateSale)
and income = gain of product + directv - spending
I want to join all these queries and calculate the income
. I tried without the table product yesterday with @Gordon Linoff here it was okay, but I was unable to combine with my new table product today.