i'm using ms sqlserver 2005. i have a query that need to filter according to date. lets say i have a table containing phone numbers and dates. i need to provide a count number of phone numbers in a time frame (begin date and end date). this phone numbers shouldn't be in the result count if they appear in the past. i'm doing something like this :
select (phoneNumber) from someTbl
where phoneNumber not in (select phoneNumber from someTbl where date<@startDate)
This is looking not efficient at all to me (and it is taking too much time to preform resulting with some side effects that maybe should be presented in a different question) i have about 300K rows in someTbl that should be checked.
after i'm doing this check i need to check one more thing. i have a past database that contains yet another 30K of phone numbers. so i'm adding
and phoneNumber not in (select pastPhoneNumber from somePastTbl)
and that really nail the coffin or the last straw that break the camel or what ever phrase you are using to explain fatal state.
So i'm looking for a better way to preform this 2 actions.
UPDATE
i have choose to go with Alexander's solution and ended up with this kind of query :
SELECT t.number
FROM tbl t
WHERE t.Date > @startDate
--this is a filter for different customers
AND t.userId in (
SELECT UserId
FROM Customer INNER JOIN UserToCustomer ON Customer.customerId = UserToCustomer.CustomerId
Where customerName = @customer
)
--this is the filter for past number
AND NOT EXISTS (
SELECT 1
FROM pastTbl t2
WHERE t2.Numbers = t.number
)
-- this is the filter for checking if the number appeared in the table before startdate
AND NOT EXISTS (
SELECT *
FROM tbl t3
WHERE t3.Date<@startDate and t.number=t3.number
)
Thanks Gilad