简体   繁体   English

SQL中多个表的总和

[英]Sum of multiple tables in SQL

I think what I want to do is fairly straightforward but the data I get back varies greatly.我认为我想做的事情相当简单,但我返回的数据差异很大。

select sum(cast(vi.qty - vi.unredeemed as bigint))
  from red.dbo.setup vc
  full join red.dbo.test bt
    on bt.batch_no = vc.batch_no
  join red.dbo.live vi
 where vi.date_issued between '2012-01-01' and '2012-01-01' 
   and vc.denom ='1' 
   and substring(vi.issue_id,3,1) = '4'

What I am trying to do is join 3 tables together then sum of qty of the results of the join and then minus the unredeemed so as to give a redeemed total in one row.我想要做的是将 3 个表连接在一起,然后将连接结果的qty相加,然后减去未赎回的qty ,以便在一行中给出赎回的总数。

I have tried various amendments to my sum field but the numbers back seem huge so I think it is multiplying them.我尝试了对 sum 字段的各种修改,但返回的数字似乎很大,所以我认为它正在乘以它们。

I haven't used joins for a while and I am a bit rusty.我有一段时间没有使用连接了,我有点生疏了。

You haven't given any condition on the second join (dbo.live) with whom you are joining.您尚未对要加入的第二个加入 (dbo.live) 提供任何条件。 Another thing is you mentioned only join.另一件事是你提到的只有加入。 Is it full or left or right joint.是全关节还是左关节或右关节。 Varies depending on your condition因您的病情而异

Your problem is that you left out the ON clause for the second JOIN您的问题是您遗漏了第二个JOINON子句

select SUM(CAST(vi.QTY -vi.unredeemed as bigint))
from red.dbo.setup vc
FULL Join red.dbo.test bt on bt.batch_no = vc.batch_no
JOIN red.dbo.live vi ON ?? -- something needs to be added here, like vi.someId =vc.someOtherId

where vi.date_issued between '2012-01-01' and '2012-01-01' and vc.denom ='1' and      SUBSTRING(vi.ISSUE_ID,3,1) ='4'

You are right, the "multiplication" effect you observed is due to the Cartesian product resulting from the missing ON clause.你是对的,你观察到的“乘法”效应是由于缺少 ON 子句导致的笛卡尔积 A simple JOIN with an unspecified ON clause results in a CROSS JOIN .带有未指定 ON 子句的简单 JOIN 会导致CROSS JOIN

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

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