我有如下表我的結果總是不正確MySQL的嵌套的總和連接和組由
表1:PRODUCT_CATEGORY
| id | title |
| 1 | Electronics |
| 2 | Kitchen |
表2:sold_items
| id | product_id | invoiceid | product_category_id | qty |
| 1 | 91 | 1001 | 1 | 2 |
| 2 | 92 | 1001 | 1 | 3 |
| 3 | 93 | 1002 | 2 | 7 |
| 4 | 94 | 1002 | 2 | 3 |
| 5 | 93 | 1003 | 2 | 15 |
表3:profit_table
| invoiceid | profit | cost |
| 1001 | 200.00 | 980.00 |
| 1002 | 100.00 | 700.00 |
| 1003 | 350.00 | 900.00 |
表4:product_log
| id | product_id | qty | tdate | invoiceid |
| 1 | 91 | 2 | 2017-01-10 | 1001 |
| 2 | 92 | 3 | 2017-01-10 | 1001 |
| 3 | 93 | 7 | 2017-02-10 | 1002 |
| 4 | 94 | 3 | 2017-02-10 | 1002 |
| 5 | 93 | 15 | 2017-03-10 | 1003 |
我要總結(profit_table.profit),MONTH(product_log.tdate),SUM(sold_items.qty) 凡結果應該是明智的PRODUCT_CATEGORY和明智的月份和條件應該像YEAR(product_log.tdate)= 2017
示例result_view
| title | MONTH(product_log.tdate) | sum(profit) |SUM(sold_items.qty) |
| Electronics| 1 | 200 | 5 |
| Kitchen | 2 | 100 | 10 |
| Kitchen | 3 | 350 | 15 |
請建議我一個正確的查詢
按我的研究成果會喜歡
SELECT r.totalqty,
f.profit,
p.mymonth,
c.title
FROM (SELECT invoiceid,Sum(qty) totalqty,product_category_id
FROM sold_items
GROUP BY sold_items.product_category_id) AS r
LEFT JOIN (SELECT invoiceid,Sum(profit) profit FROM profit_table GROUP BY profit_table.invoiceid) AS f ON r.tid = f.tid
LEFT JOIN (SELECT tid,DATE(tdate) mymonth FROM pstatements) AS p
ON r.invoiceid = p.invoiceid
LEFT JOIN (SELECT id,title FROM product_category) AS c
ON r.product_category_id = c.id
WHERE YEAR(p.mymonth)='2017' GROUP BY DATE(p.tdate)
這不是一個正確的結果,如果你想回答仍然是一個線索
那你試試這麼遠嗎?你得到了哪個不正確的結果? – Hugo
我已經嘗試了很多組合,有時我得到了雙倍的總和,也沒有得到正確的組。如果你可以寫比請寫一個查詢來實現例子result_view – Piyush
@SatishGarg先生的計算是不正確的,因爲你正在做一個簡單的left_join另外你可以給我表結構的建議。 – Piyush