I’m attempting to evaluate how many times a transaction is started in a given month in our system for a reconciliation process.
A Transaction Reference can be created in a previous month so I am trying to exclude those transactions from the final count – the first thought was to use a “WHERE IN” type approach, but the outcome is always 0 which is definitely wrong as when I execute the queries in isolation, there are entries in the subquery which should be excluded.
I have read that “WHERE IN” type queries aren’t reliable especially when there are large data sets returned in the subquery, but I don’t know how to rework this one to achieve the goal in this case, and going forward if this way of doing it is flawed which it appears to be.
Current query is shown below – thanks for your help:
SELECT Count(DISTINCT TransactionRef)
FROM Payments
WHERE Month(PaymentDate) = 8
AND Year(PaymentDate) = 2011
AND TransactionRef NOT IN
(SELECT DISTINCT TransactionRef
FROM Payments WHERE PaymentDate < '20110801')
EDIT
OK further to answers, it seems a null value was doing me wrong… thanks – here is the edited code in case anyone stumbles here in future:
SELECT Count(DISTINCT TransactionRef)
FROM Payments
WHERE Month(PaymentDate) = 8
AND Year(PaymentDate) = 2011
AND TransactionRef NOT IN
(SELECT DISTINCT TransactionRef
FROM Payments WHERE TransactionRef IS NOT NULL AND PaymentDate < '20110801')
if the column TransactionRef has any null in it the not in will return false.
use Exists.
if NULLs are not your problem then you’ll have to give us mroe info