I need a SQL statement to extract those applicants from the database who have both the attachment tags. The belowq statement works fine if I want aaplicant who have either 7 or 8 as the attachment tag but i need applicant who have both these tags.
select distinct(a.id) from applicant a
join applicantdeployment ad on a.id = ad.applicantid
join ApplicantAttachment at on a.id = at.applicantid
where a.applicanttype = 'TCN/LN' and ad.groundlocation in (4,8,14) and ad.deploymentstatus =1
and ad.trainingdeploymentstatus = 6 and at.tag in (7,8)
For example from the below set I just want ids 7332,7451 and 7449 to show up.
ID Tag
7328 8
7328 8
7332 8
7332 7
7337 7
7449 8
7449 7
7451 8
7453 7
7451 7
Thanks!
You could join to the ApplicationAttachment table twice to ensure that both tags are present. That way you would avoid the need for DISTINCT and GROUP BY.
SELECT a.id
FROM applicant a
JOIN applicantdeployment ad ON a.id = ad.applicantid
JOIN ApplicantAttachment at7 ON a.id = at7.applicantid AND at7.tag = 7
JOIN ApplicantAttachment at8 ON a.id = at8.applicantid AND at8.tag = 8
WHERE a.applicanttype = 'TCN/LN'
AND ad.groundlocation IN (4,8,14)
AND ad.deploymentstatus = 1
AND ad.trainingdeploymentstatus = 6