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中输入所有行
答案 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