简体   繁体   English

如何在 SQL 中使用两个表进行聚合?

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

I have two tables, one has products shipped in and other table where product is shipped out.我有两张桌子,一张有产品运入,另一张桌子有产品运出。 I just need to have a total number of product still not shipped.我只需要总数量的产品仍未发货。 It can be easily done by calculating the difference but I am facing some issues.通过计算差异可以轻松完成,但我面临一些问题。

Stock In Flow Table:流量表中的库存:

Product ID产品编号 Quantity In数量
1 1 15 15
1 1 5 5
2 2 5 5
2 2 10 10
3 3 15 15
4 4 5 5

Stock Out Flow Table:缺货流程表:

Product ID产品编号 Quantity Out数量输出
1 1 7 7
2 2 3 3
3 3 5 5
2 2 2 2
1 1 8 8
2 2 2 2
1 1 5 5
3 3 3 3

I am using this query我正在使用这个查询

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"

The desired result should be this期望的结果应该是这样

Product ID产品编号 InStock有存货
1 1 0 0
2 2 8 8
3 3 7 7
4 4 5 5

However The numbers are not correct.但是数字不正确。 It is adding up all the numbers multiple times.它多次将所有数字相加。 I have tried multiple joins but still not getting the desired result.我尝试了多次连接,但仍然没有得到想要的结果。 Please help me to check where I am going wrong?请帮我检查我哪里出错了?

You need to aggregate each table first and using an outer query to do the calculations.您需要先聚合每个表并使用外部查询进行计算。 The problem you might face is the use of LEFT JOIN which in your case will give null for id 4 because 5-null gives null.您可能面临的问题是使用 LEFT JOIN 在您的情况下将为 id 4 给出 null,因为 5-null 给出 null。 To solve that use a case condition , when tot_quantity_out is null then get tot_quantity_in value.为了解决这个问题,使用 case 条件,当 tot_quantity_out 为 null 时,获取 tot_quantity_in 值。

Try:尝试:

   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 https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=c0fba72a3a1b72d651d04bbb9447665c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM