I have a query where the result doesn't make sense. Please review the query below. If I change Line #4 from demandnumber >= 28500 to 28554 the query result increases from 0 to 30. This is not mathematically possible?
The query also perfoms correctly if I remove the 2nd part of the union in the sub query.
declare @CL int
select @CL = codeid from codes where codetyp = 'BTSTATUS' and coderef = 'CL'
select count(*) from paymentdemands where
demandnumber >= 28550 and
owntyp = 'ME' and ownid in
(select ownid from feedetails fd
join codes fpt on fd.paymenttermsid = fpt.codeid and fpt.coderef = 'DFSA'
left join bankaccounts ba on fd.sourcebankaccid = ba.bankaccid
left join banks b on ba.bankid = b.bankid and b.sortcode = '124267'
left join banktransactions bt on ba.bankaccid = bt.bankaccid and bt.statusid = @CL
where owntyp = 'ME' and bt.banktxnid is null
union
select ownid from feedetails fd
join codes fpt on fd.paymenttermsid = fpt.codeid
where owntyp = 'ME' and fpt.coderef = 'DFSA' and fd.sourcebankaccID is null
)
The query also perfoms correctly if I remove the 2nd part of the union in the sub query.
declare @CL int
select @CL = codeid from codes where codetyp = 'BTSTATUS' and coderef = 'CL'
select count(*) from paymentdemands where
demandnumber >= 28550 and
owntyp = 'ME' and ownid in
(select ownid from feedetails fd
join codes fpt on fd.paymenttermsid = fpt.codeid and fpt.coderef = 'DFSA'
left join bankaccounts ba on fd.sourcebankaccid = ba.bankaccid
left join banks b on ba.bankid = b.bankid and b.sortcode = '124267'
left join banktransactions bt on ba.bankaccid = bt.bankaccid and bt.statusid = @CL
where owntyp = 'ME' and bt.banktxnid is null
union
select ownid from feedetails fd
join codes fpt on fd.paymenttermsid = fpt.codeid
where owntyp = 'ME' and fpt.coderef = 'DFSA' and fd.sourcebankaccID is null
)