从两个结果集查询中获取一个结果表

时间:2013-09-01 07:04:15

标签: sql sql-server-2005

查询1:

select EmpID, count(ProgramId) as "TotalPrograms", 
             SUM(Cast([NoOfDays] as INT) ) as "Total No of Days"  
             from **EmpTrainingInfo**  group by EmpID

结果输出:EmpID总计划,总天数

查询2:

select  AssignedTo [EmpID]  ,count(ProgramId) as "Total Foreign Visits" 
          from **ProgramInfo** where status in ('Completed','Assigned') 
          and Country NOT IN ('Country1','Kountry1 ','cntry1')   group by AssignedTo 

结果输出:EmpID,外国访问总数

如何将这两者结合起来以在一个表中获取输出列:

 **EmpID** , **Total Programs** ,**Total No Of Days**,Total Foreign Visits

任何提示都将受到赞赏..

2 个答案:

答案 0 :(得分:1)

更新根据您在评论中的后续问题

SELECT COALESCE(q1.EmpID, q2.EmpID) EmpID, -- if its a INNER JOIN use just q1.EmpID
       q1.TotalPrograms, 
       q1.TotalNoofDays, 
       q2.TotalForeignVisits, 
       q2.TotalHomeVisits
  FROM
(
    SELECT EmpID, COUNT(ProgramId) AS TotalPrograms, 
           SUM(Cast([NoOfDays] AS INT) ) AS TotalNoofDays
      FROM EmpTrainingInfo
     GROUP BY EmpID
) q1 FULL OUTER JOIN -- it might be just JOIN depending on your data setup
(
    SELECT AssignedTo EmpID, 
           SUM(CASE WHEN Country NOT IN ('Country1','Kountry1 ','cntry1') THEN 1 ELSE 0 END) AS TotalForeignVisits,
           SUM(CASE WHEN Country     IN ('Country1','Kountry1 ','cntry1') THEN 1 ELSE 0 END) AS TotalHomeVisits
      FROM ProgramInfo
     WHERE status IN ('Completed','Assigned') 
    GROUP BY AssignedTo
) q2 ON q1.EmpID = q2.EmpID

答案 1 :(得分:0)

由于两个表通过两个字段EmpTrainingInfo.EmpId = ProgramInfo.AssignedTo相互关联,因此您需要JOIN这两个字段SELECT e.EmpID, COUNT(ProgramId) AS "TotalPrograms", SUM(Cast([NoOfDays] as INT) ) AS "Total No of Days" , COUNT(ProgramId) AS "Total Foreign Visits" FROM EmpTrainingInfo AS e INNER JOIN ProgramInfo AS p ON e.EmpId = p.AssignedTo GROUP BY e.EmpID; ,如下所示:

{{1}}