我正在使用MSSQL Server 2008。 我有三张表如下:
表格:项目 列:ProjectID,{Primary Key} ProjectNickName,BusinessType
表格:审计 列:{外键} ProjectNickName,{主键} AuditID,AuditCreationDate,AuditStatus
表格:发现 列:{外键} AuditID,FindingStatus,{主键} FindingNumber
审计项目:一对多
审核结果:一对多
我想查找审计记录为“Open”的所有审计记录,这些记录在“Open”FindingStatus中没有任何结果。此外,审计记录必须与BusinessType为“External”且AuditCreationDate在过去30天内的项目相关联。
这是我到目前为止所做的:
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'
上述查询存在两个问题。
我猜我可能需要使用某种具有不同功能的嵌套查询,但我无法理解如何做到这一点。
非常感谢任何帮助!我试图尽可能清晰和准确,但如果我能详细说明,请告诉我。
答案 0 :(得分:2)
Select
a.AuditID,
p.BusinessType,
p.ProjectNickName,
a.AuditCreationDate
FROM
Project p
JOIN
Audit a
ON p.ProjectNickName = a.ProjectNickName AND
a.AuditCreationDate >= GETDATE()-30 AND
a.AuditStatus ='OPEN'
LEFT JOIN
Findings f
on a.AuditID = f.AuditID and
f.FindingStatus ='OPEN'
WHERE
p.BusinessType ='External' AND
f.FindingStatus is null -- Here we could use any column name from the findings table. We are basically saying we don't want there to exist an associated findings entry that has the findingStatus open
答案 1 :(得分:1)
您可以使用not exists
子查询来排除具有未决结果的审核。这也将消除每次审核的多行,因为您不再加入调查结果表。
select a.AuditID
, p.BusinessType
, p.ProjectNickName
, a.AuditCreationDate
from Project p
join Audit a
on p.ProjectNickName = a.ProjectNickName
where p.BusinessType LIKE 'External' and
a.AuditStatus LIKE 'OPEN' and
a.AuditCreationDate >= getdate()-30 and
not exists
(
select *
from Findings f
where a.AuditID = f.AuditID and
f.FindingStatus = 'OPEN'
)
答案 2 :(得分:0)
您可以使用相关的子查询,例如此子查询。
SELECT * FROM Audit A WHERE AuditID NOT IN
(SELECT AuditID FROM Findings
WHERE AuditID = A.AuditID and Status = 'OPEN')
应该禁止任何具有状态='打开'的结果的审核
您需要使用Project JOIN等完成它。
答案 3 :(得分:0)
如果审计在发现表中根本没有行(即将使用左外连接返回null),则未指定是否有必要显示该行。假设你确实希望它们显示,这是一种方法。
Select a.AuditID, p.BusinessType, p.ProjectNickName, a.AuditCreationDate
FROM Project p
INNER JOIN Audit a ON p.ProjectNickName = a.ProjectNickName
WHERE p.BusinessType LIKE 'External'
AND AuditCreationDate >= GETDATE()-30
AND a.AuditStatus LIKE 'OPEN'
AND a.AuditID NOT IN
(select distinct AuditID from Findings
where FindingStatus LIKE 'OPEN')