如何结合两个sql查询结果

时间:2014-01-27 16:10:30

标签: sql sql-server sql-server-2008

我设计了以下两个查询,我可以使用左外连接将它们连接起来以获得所需的结果,但有没有办法只编写一个查询来获得相同的结果?我该如何简化呢。

First Query带来了参与该项目的人员总数,第二个查询仅显示那些参与该项目但属于不同办公室的人员。

首次质询

SELECT  
VisitDate =  LEFT(Datename(month,v.VisitDate),3)
,COUNT( distinct i.InspectorID) AS TotalUsed

 FROM Visits v 
 INNER JOIN InspectionScope insp ON insp.AssignmentID = v.AssignmentID 
 INNER JOIN Assignments a ON a.AssignmentID = insp.AssignmentID  
 INNER JOIN Inspectors i ON i.InspectorID = insp.InspectorID 

 WHERE a.ClientID IN (22,33)
 Group by Datename(month,v.VisitDate)

第二次查询

SELECT 
 VisitDate =  LEFT(Datename(month,v.VisitDate),3)
,COUNT( distinct i.InspectorID) AS TotalContractorUsed

 FROM Visits v 
 INNER JOIN InspectionScope insp ON insp.AssignmentID = v.AssignmentID 
 INNER JOIN Assignments a ON a.AssignmentID = insp.AssignmentID  
 INNER JOIN Inspectors i ON i.InspectorID = insp.InspectorID 

 WHERE a.ClientID IN (22,33)
 **AND i.OfficeID  IN (5)**

Group by Datename(month,v.VisitDate)

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以在单个查询中使用条件聚合:

SELECT  VisitDate = LEFT(Datename(month,v.VisitDate),3), 
        COUNT( distinct i.InspectorID) AS TotalUsed,
        COUNT(distinct case when i.OfficeID  IN (5) then i.InspectorID end) AS TotalContractorUsed
FROM Visits v 
 INNER JOIN InspectionScope insp ON insp.AssignmentID = v.AssignmentID 
 INNER JOIN Assignments a ON a.AssignmentID = insp.AssignmentID  
 INNER JOIN Inspectors i ON i.InspectorID = insp.InspectorID 
WHERE a.ClientID IN (22,33)
Group by Datename(month,v.VisitDate);

答案 1 :(得分:0)

我还没有执行查询。请检查。

;WITH CTE (VisitDate, TotalUsed) AS
(SELECT  
VisitDate =  LEFT(Datename(month,v.VisitDate),3)
,COUNT( distinct i.InspectorID) AS TotalUsed

 FROM Visits v 
 INNER JOIN InspectionScope insp ON insp.AssignmentID = v.AssignmentID 
 INNER JOIN Assignments a ON a.AssignmentID = insp.AssignmentID  
 INNER JOIN Inspectors i ON i.InspectorID = insp.InspectorID 
 WHERE a.ClientID IN (22,33)
 Group by Datename(month,v.VisitDate))

SELECT 
CTE.VisitDate
 ,CTE.TotalUsed
 ,ISNULL(COUNT(distinct i.InspectorID),0) AS TotalContractorUsed
FROM CTE 
LEFT JOIN  Visits v ON CTE.VisitDate = v.VisitDate
INNER JOIN InspectionScope insp ON insp.AssignmentID = v.AssignmentID 
INNER JOIN Assignments a ON a.AssignmentID = insp.AssignmentID  
INNER JOIN Inspectors i ON i.InspectorID = insp.InspectorID 
WHERE a.ClientID IN (22,33)  AND i.OfficeID  IN (5)
Group by Datename(month,v.VisitDate)