简体   繁体   中英

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.

I have tried various amendments to my sum field but the numbers back seem huge so I think it is multiplying them.

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. 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

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. A simple JOIN with an unspecified ON clause results in a CROSS JOIN .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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