簡體   English   中英

如何在 SQL 中使用兩個表進行聚合?

[英]How do I aggregate using two tables in SQL?

我有兩張桌子,一張有產品運入,另一張桌子有產品運出。 我只需要總數量的產品仍未發貨。 通過計算差異可以輕松完成,但我面臨一些問題。

流量表中的庫存:

產品編號 數量
1 15
1 5
2 5
2 10
3 15
4 5

缺貨流程表:

產品編號 數量輸出
1 7
2 3
3 5
2 2
1 8
2 2
1 5
3 3

我正在使用這個查詢

SELECT
         "Stock In Flow Table"."Product ID" 'Product ID',
         sum("Stock In Flow Table"."Quantity In") as "Quantity In",
         sum("Stock Out Flow Table"."Quantity Out") as "Quantity Out",
        "Quantity In" -"Quantity Out" as "InStock"
FROM  "Stock In Flow Table"
JOIN "Stock Out Flow Table" ON "Stock Out Flow Table"."Product ID"  = "Stock In Flow Table"."Product ID"  
GROUP BY  "Product ID", "InStock"

期望的結果應該是這樣

產品編號 有存貨
1 0
2 8
3 7
4 5

但是數字不正確。 它多次將所有數字相加。 我嘗試了多次連接,但仍然沒有得到想要的結果。 請幫我檢查我哪里出錯了?

您需要先聚合每個表並使用外部查詢進行計算。 您可能面臨的問題是使用 LEFT JOIN 在您的情況下將為 id 4 給出 null,因為 5-null 給出 null。 為了解決這個問題,使用 case 條件,當 tot_quantity_out 為 null 時,獲取 tot_quantity_in 值。

嘗試:

   select t1.product_id,
       case when tot_quantity_out is null then tot_quantity_in else tot_quantity_in - tot_quantity_out end as InStock
from ( select product_id,sum(quantity_in) as tot_quantity_in
       from stock_in 
       group by product_id 
     ) as t1 
left join 
     ( select product_id,sum(quantity_out) as tot_quantity_out
       from stock_out 
       group by product_id
     ) as t2 on t1.product_id=t2.product_id;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=c0fba72a3a1b72d651d04bbb9447665c

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM