I am using MSSQL Server 2008. I have three tables as follows:
Table:Project Columns: ProjectID, {Primary Key} ProjectNickName, BusinessType
Table:Audit Columns: {Foreign Key}ProjectNickName, {Primary Key}AuditID, AuditCreationDate, AuditStatus
Table:Findings Columns: {Foreign Key}AuditID, FindingStatus, {Primary Key}FindingNumber
Project to Audit: One to many
Audit to Findings: One to many
I want to find all audit records with an AuditStatus of 'Open' that have NO findings with an 'Open' FindingStatus. Also the audit record must be associated with a project that has a BusinessType of 'External' and the AuditCreationDate is within the last 30 days.
Here is what I have so far:
Select a.AuditID, p.BusinessType, p.ProjectNickName, a.AuditCreationDate
FROM Project p
INNER JOIN Audit a ON p.ProjectNickName = a.ProjectNickName
LEFT OUTER JOIN Findings f on a.AuditID = f.AuditID
WHERE p.BusinessType LIKE 'External' AND AuditCreationDate >= GETDATE()-30
AND a.AuditStatus LIKE 'OPEN' and f.FindingStatus NOT LIKE 'OPEN'
There are two problems with the above query.
- There can be multiple findings for each audit, but if any one of those findings has a status of 'Open', I do not want that record to show.
- The above does not show disctinct audit records. If there are multiple findings for an audit that do not have an 'Open' status, it will show them. I only want distinct audit records. I looked at the following DISTINCT for only one Column, which solved that problem, but an audit record would still show if there was at least one finding that did not have an 'Open' findingStatus and another finding associated with the audit that DID have an 'Open' findingStatus. As mentioned previously, I only want audits that have no finding records with a findingStatus of 'Open' to appear in my result set.
I am guessing I may need to use some kind of nested query with a distinct function, but I can't wrap my mind around how to do it yet.
Any help is much appreciated! I tried to be as clear and precise as possible, but let me know if I can elaborate on anything.