0

查询 1:

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

结果输出: EmpID Total Programs ,Total No Of Days

查询 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

任何提示将不胜感激..

4

2 回答 2

1

UPDATED Based on your follow up question in comments

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
于 2013-09-01T07:22:49.480 回答
0

Since the two tables relate to each other by the tow fields EmpTrainingInfo.EmpId = ProgramInfo.AssignedTo, then you need to JOIN the two tables using these two fields like this :

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;
于 2013-09-01T07:23:58.093 回答