我有3张桌子如下:
我使用join product & product_sales_branch_a来获得销售数量,使用以下脚本:
select A.product_desc, sum(B.qty) from product A
join product_sales_branch_a B on B.product_id = A.product_id
where A.product_id = 'ABC*'结果:
product_desc | sum(B.qty)
1234 | 16结果正确返回。
然后,我使用join product & product_sales_branch_b来使用以下脚本获得销售数量:
select A.product_desc, sum(C.qty) from product A
join product_sales_branch_b C on C.product_id = A.product_id
where A.product_id = 'ABC'结果:
product_desc | sum(C.qty)
1234 | 20结果也正确返回。
但是现在,我试图通过以下脚本加入3表:
select A.product_desc, sum(B.qty), sum(C.qty) from product A
join product_sales_branch_a B on B.product_id = A.product_id
join product_sales_branch_b C on C.product_id = A.product_id
where A.product_id = 'ABC'结果:
product_desc | sum(B.qty) | sum(C.qty)
1234 | 288 | 280这不是我所期望的结果。
我的sql查询有什么问题吗?
发布于 2014-12-30 10:43:08
在这种情况下,我会选择分选:
select A.product_desc,
(select sum(B.qty) from product_sales_branch_a B where B.product_id = A.product_id),
(select sum(C.qty) from product_sales_branch_b C where C.product_id = A.product_id)
from product A
where A.product_id = 'ABC'发布于 2014-12-30 10:54:03
问题是,当您加入第三个表时,第二个表和第三个表之间没有任何关系。因此,如果表1和表2的联接返回m行,而1和3的联接返回n行,则将得到m*n行作为输出。这就是为什么你的总和比预期的要大得多。
解决这个问题的一种方法是使用count distinct,如果您非常确定qty没有重复值的话。但是,这在实际数据中不太可能,因此您应该考虑使用上面@jarlh建议的子查询方法:
select A.product_desc as desc,
(select sum(B.qty) from product_sales_branch_a B where B.product_id = A.product_id and A.product_id = 'ABC') as bqty,
(select sum(C.qty) from product_sales_branch_b C where C.product_id = A.product_id and A.product_id = 'ABC') as cqty
from product Ahttps://stackoverflow.com/questions/27703837
复制相似问题