1

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.

4

2 回答 2

1

您没有对您要加入的第二个加入 (dbo.live) 给出任何条件。另一件事是你提到只加入。它是完整的还是左关节或右关节。因您的情况而异

于 2012-11-08T11:28:10.340 回答
1

您的问题是您遗漏了ON第二个子句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'

你是对的,你观察到的“乘法”效应是由于缺少 ON 子句导致的笛卡尔积。带有未指定 ON 子句的简单 JOIN 会导致CROSS JOIN

于 2012-11-08T11:28:28.627 回答