简体   繁体   中英

t-sql query that returns missing records

I have a query (ContactFormTypesRequired) that returns ContactID and FormTypeID utilizing related tables that are not shown below. This is a list of FormTypes that each Contact should have related to it as a Form.

I need a query that returns Contacts that do not have one or more related forms of the FormTypes specified in the above query.

I've tried a left outer join from Form to ContactsFormTypesRequired on FormTypeID, but the results don't take into account FormTypes that each specific Contact should have.

Please let me know if you have any questions.

Thank you in advance for any suggestions.

模式

I am writing the query this way. This first starts with your query to get needed forms as a CTE, then cross joins them to Contacts to get every needed combination, before left joining to the actual forms.

with NeededForms (<yourqueryhere>)
select distinct c.*
from Contact c cross join
     NeededForms nf left outer join
     Form F
     on nf.FormTypeId = f.FormTypeId left outer join
     ContactForm cf
     on c.ContactId = cf.ContactId and
        f.FormId = cf.FormId
where cf.FormId is null

I'm doing it this way, so you can answer the query of what forms are missing with a very similar query:

with NeededForms (<yourqueryhere>)
select c.*, nf.FormTypeId
from Contact c cross join
     NeededForms nf left outer join
     Form F
     on nf.FormTypeId = f.FormTypeId left outer join
     ContactForm cf
     on c.ContactId = cf.ContactId and
        f.FormId = cf.FormId
where cf.FormId is null

Try this simple query using NOT IN Cluase:

SELECT * FROM Contact
WHERE ContactID IN 
(SELECT ContactID FROM ContactForm 
INNER JOIN FORM ON ContactForm.FormID=Form.FormID
WHERE FormTypeID=@FormTypeID)

I created ContactFormTypeExist:

SELECT DISTINCT Contact.ContactID, Form.FormTypeID
FROM Contact 
    INNER JOIN ContactForm 
        ON Contact.ContactID = ContactForm.ContactID 
    INNER JOIN Form 
        ON ContactForm.FormID = Form.FormID

Then joined ContactFormTypesRequired described in the question above to ContactFormTypeExist with outer join to give me the ConactIDs that are missing related FormTypeIDs:

SELECT ContactFormTypesRequired.ConactID
FROM ContactFormTypeExist 
    RIGHT JOIN ContactFormTypesRequired 
        ON (ContactFormTypeExist.FormTypeID = ContactFormTypesRequired.FormTypeID) 
            AND (ContactFormTypeExist.ConactID = ContactFormTypesRequired.ConactID)
WHERE (((ContactFormTypeExist.ConactID) Is Null));

This returns all the ContactID for Contacts missing FormTypes required by their ContactType.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM