将where子句添加到T-sql LEFT OUTER JOIN查询的问题

时间:2010-05-04 09:59:56

标签: sql-server-2005 tsql

SELECT TOP (100) PERCENT dbo.EmployeeInfo.id, MIN(dbo.EmployeeInfo.EmpNo) AS EmpNo, 
            SUM(dbo.LeaveApplications.DaysAuthorised) AS DaysTaken
FROM  dbo.EmployeeInfo LEFT OUTER JOIN dbo.LeaveApplications ON 
           dbo.EmployeeInfo.id = dbo.LeaveApplications.EmployeeID
WHERE (YEAR(dbo.LeaveApplications.ApplicationDate) = YEAR(GETDATE()))
GROUP BY dbo.EmployeeInfo.id, dbo.EmployeeMaster.EmpNo
ORDER BY DaysTaken DESC 

我想要的基本功能是检索表dbo.EmployeeInfo中的所有记录,而不管表dbo.LeaveApplications中是否存在相应的记录。如果EmployeeInfo中的一行在LeaveApplications中没有相关行,我想将其SUM(dbo.LeaveApplications.DaysAuthorised) AS DaysTaken列作为NULL返回,或者甚至可以将其返回0.

通过上面的查询,如果我删除where条件,我能够实现我想要的,但问题是我也想要仅在ApplicationDate在当前年份时从LeaveApplication返回相关行。

现在添加了where条件,只有在LeaveApplications中有相应的行时才能从EmployeeInfo获取行,但我只想在EmployeeInfo中输入所有行

1 个答案:

答案 0 :(得分:0)

您可以在NULL子句中为WHERE添加测试,这可能会导致SUM返回NULL以及LeaveApplications上不存在的行{1}}表:

SELECT TOP (100) PERCENT dbo.EmployeeInfo.id, MIN(dbo.EmployeeInfo.EmpNo) AS EmpNo, 
            SUM(dbo.LeaveApplications.DaysAuthorised) AS DaysTaken
FROM  dbo.EmployeeInfo LEFT OUTER JOIN dbo.LeaveApplications ON 
           dbo.EmployeeInfo.id = dbo.LeaveApplications.EmployeeID
WHERE (YEAR(dbo.LeaveApplications.ApplicationDate) = YEAR(GETDATE()))
      OR dbo.LeaveApplications.ApplicationDate IS NULL
GROUP BY dbo.EmployeeInfo.id, dbo.EmployeeMaster.EmpNo
ORDER BY DaysTaken DESC