我有一个查询,它从受影响的表和支持表中查找应用程序。第三个表包含了我需要查询的更多项目信息。其中一个是状态字段。我想为该Project表添加一个连接,并且仅当状态显示为In Progress时才返回结果。这就是我到目前为止所做的:
数据和列的示例
以下申请信息
Appid ProjectId
197 251
以下的项目信息栏
ProjectID ProjectName ImplementationDate Status
select AppId = a.AppId,
ApplicationName = a.ApplicationName
from Applications a
left join ( select AppId = t.AppId ,
Cnt = count(*)
from ImpactedApplications t
group by t.AppId
) ia on ia.AppId = a.AppId
left join ( select AppId = t.AppId ,
Cnt = count(*)
from SupportingApplications t
group by t.AppId
) sa on sa.AppId = a.AppId
where sa.Cnt > 0 OR ia.Cnt > 0 ORDER BY ApplicationName ASC
答案 0 :(得分:0)
CTE方法
WITH CTE(appid,ApplicationName,ProjectId) 如 (
select AppId = a.AppId,
ApplicationName = a.ApplicationName,
ProjectId = a.ProjectId
from Applications a
left join ( select AppId = t.AppId
Cnt = count(*)
from ImpactedApplications t
group by t.AppId
) ia on ia.AppId = a.AppId
left join ( select AppId = t.AppId
Cnt = count(*)
from SupportingApplications t
group by t.AppId
) sa on sa.AppId = a.AppId
where sa.Cnt > 0 OR ia.Cnt > 0 ORDER BY ApplicationName ASC
)
select * from CTE C
INNER JOIN Porject P
on C.ProjectId = P.ProjectID
and P.Status = 'InProgress'
UNION可能会在这里工作
SELECT ApplicationName , P.*
FROM Applications A
INNER JOIN ImpactedApplications IA
on A.AppId = IA.AppId
INNER JOIN Project P
on IA.ProjectId = P.ProjectID
AND P.Status ='InProgress'
UNION
SELECT ApplicationName , P.*
FROM Applications A
INNER JOIN SupportingApplications SA
on A.AppId = SA.AppId
INNER JOIN Project P
on IA.ProjectId = P.ProjectID
AND P.Status ='InProgress'
order by ApplicationName ASC
答案 1 :(得分:0)
如果我对现有代码没有错,你需要在两个表上基于projectid将项目表与应用程序表连接起来,只需要获取status = InProgress的记录。
select AppId = a.AppId,
ApplicationName = a.ApplicationName,
p.*
from Applications a
left join ( select AppId = t.AppId ,
Cnt = count(*)
from ImpactedApplications t
group by t.AppId
) ia on ia.AppId = a.AppId
left join ( select AppId = t.AppId ,
Cnt = count(*)
from SupportingApplications t
group by t.AppId
) sa on sa.AppId = a.AppId
join project p on a.projectid=p.projectid
where (sa.Cnt > 0 OR ia.Cnt > 0 )
and p.status='InProgress'
ORDER BY ApplicationName ASC