Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Finding Non-Matching Records

Author  Topic 

evanburen
Posting Yak Master

167 Posts

Posted - 2014-12-16 : 15:35:21
Hi

I have two tables joined by the field name 'PCA' and I want to get a list of records which do not appear in the table named DataRequests (the first table) for a particular ReportPeriod.



For example, this produces the records that I want. Every PCA except ConServe, EOS-Collecto and Allied would be in my results.

SELECT
PCAs.PCA
FROM
DataRequests RIGHT OUTER JOIN PCAs ON DataRequests.PCA = PCAs.PCA
WHERE
(DataRequests.PCA IS NULL)

However, what I really need is every record which does not appear in the DataRequest table for a given ReportPeriod. So if @ReportPeriod = '12/15/2014' my results would be every PCA except Conserver and EOS-Collecto

Allied Interstate
Account Control Technology
CBE Group
Coast Prof
Collection Tech
Delta Mgmt
Diversified
Enterprise Recovery


SELECT
PCAs.PCA
FROM
DataRequests RIGHT OUTER JOIN PCAs ON DataRequests.PCA = PCAs.PCA
WHERE
(DataRequests.PCA IS NULL) AND [ReportPeriod] = @ReportPeriod

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2014-12-16 : 16:31:44
use one of these
SELECT
PCAs.PCA
FROM
PCAs
LEFT JOIN DataRequests r ON
r.ReportPeriod = @ReportPeriod
AND r.PCA = PCAs.PCA
WHERE
r.PCA IS NULL;


SELECT PCAs.PCA
FROM
PCAs
WHERE
NOT EXISTS
( SELECT * FROM DataRequests r
WHERE r.PCA = PCAs.PCA
AND r.ReportPeriod = @ReportPeriod
)
If there can be more than one record in the DataRequests table for a given PCA and ReportPeriod, you must use the second query.
Go to Top of Page
   

- Advertisement -