2014-09-23 45 views
0

我有一個查詢可以從受影響的表和支持表中查找應用程序。還有第三個表格,其中包含我需要查詢的更多項目信息。其中之一是地位領域。我想將連接添加到該Project表中,並且只有當狀態顯示爲「正在進行」時才返回結果。這是我到目前爲止有:數據將狀態檢查添加到多個表查詢

例和列

下面

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

你可以從應用程序中提供樣本數據,我mpactedApplications,SupportingApplications表 – radar 2014-09-23 15:55:42

+0

@Rajesh在我的原始文章中添加了帶有示例的信息。希望這可以幫助! – OnceorTwice 2014-09-23 17:06:07

+0

根據列更新了我的答案,你可以檢查這是否適用於你 – radar 2014-09-23 17:19:46

回答

0

CTE方法

; WITH CTE(APPID,應用程序名稱,專案編號) AS (

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 
0

則需根據加盟項目表申請表on projectid on both table and only need to retrieve records have where 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 
+0

你能演示嗎?這些表格是支持應用程序和項目的受影響應用程序 – OnceorTwice 2014-09-24 13:13:38

+0

@OnceorTwice,根據您的代碼,您甚至有應用程序表的權利?和應用程序和項目都投影了我加入並把條件狀態='InProgress' – 2014-09-24 16:40:16