[英]MySQL nested sums with multiple joins and group by
我有以下表格,我的結果總是不正確
表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)
如果您要回答,這不是正確的結果,仍然是一個線索
下面的書面查詢應該可以工作。
select pc.title, month(pl.tdate), pt.profit, sum(si.qty)
from product_category pc
inner join sold_items si on si.product_category_id = pc.id
inner join profit_table pt on pt.invoiceid = si.invoiceid
inner join product_log pl on pl.invoiceid = pt.invoiceid
where si.product_id = pl.product_id
group by pc.title,pl.tdate
order by month(pl.tdate) asc ;
您應該使用SOME JOIN AND group by
select
product_category.title
, MONTH(product_log.tdate)
, sum(profit)
, SUM(sold_items.qty)
from product_category
left join sold_items on sold_items.product_category_id = product_category.id
left join product_log on product_log.product_id = sold_items.product_id
left join profit_table on profit_table.invoiceid = product_log.invoiceid
group by product_category.title, MONTH(product_log.tdate)
您需要將表連接到它們的鍵上,並按產品和交易月份進行分組。 類似於以下內容:
select pc.title, month(pl.tdate) as tmonth, sum(pt.profit) as month_profit, sum(si.qty) as month_qty
from product_category pc
left join sold_items si
on si.product_category_id = pc.id
left join profit_table pt
on pt.invoice_id = si.invoice_id
left join product_log pl
on pl.product_id = si.product_id
and pl.invoice_id = si.invoice_id
group by pc.id, month(pl.tdate)
where year(pl.tdate) = '2017';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.