在这种情况下 SQL 连接的总和可以正常工作吗?

问题描述 投票:0回答:1

我想在给定两个条件的情况下从内部 JOIN 获取 SUM:prod_cat = 'Clothing' 和 prod_subcat = 'Kids'。这两个表如下所示:

enter image description here.

我写了这个:

enter image description here

我得到 6251137.49。

我可以在不使用内部 JOIN 的情况下完美地得到 SUM,只需使用这个:

enter image description here

但是,当我运行这两个查询时,我得到了不同的结果:

enter image description here

正确答案是2110959.95。您能帮我看看使用内部 JOIN 时可能出现的问题吗?

sql sql-server inner-join
1个回答
-1
投票
select round(sum(total_amt),2) as Amount
from Transactions t
where exists (select * from prod_cat_info p
   where t.prod_cat_code = p.prod_cat_code and
         t.prod_subcat_code = p.prod_subcat_code and
         p.prod_cat = 'Clothing' and
         p.prod_subcat = 'Kids');

这只是一种方法,还有很多方法。

如果您的关系是一对多,那么简单的连接也可以工作。

© www.soinside.com 2019 - 2024. All rights reserved.