簡體   English   中英

SQL 左連接不包括左表中的所有記錄

[英]SQL left join is not including all records from left table

我有一個要求,讓每個員工每月完成不同任務的總小時數。 為此,我正在編寫一個存儲過程。 但是左連接沒有填充員工表中的所有記錄。 我知道 where 條件正在過濾掉 null 值,但我真的不知道如何克服這個問題。

ALTER PROCEDURE [dbo].[GetEmployeeWorkHours]
@PageSize smallint = 10,
@CurrentPage smallint = 1,
@EmployeeId varchar(1000) = null,
@StartDate datetime = null,
@EndDate datetime = null
AS

 BEGIN

if(@StartDate is null)
select @StartDate = DATEADD(month, DATEDIFF(month, 0, getDate()), 0)

if(@EndDate is null)
select @EndDate = getDate()

select   e.Id,
e.FirstName + ' ' + e.LastName as [Name],
sum([Minutes]/60.0) as [WorkedHours]
from Employees e
left join TaskResources tr on (e.Id = tr.EmployeeId)
inner join ResourceTaskSchedules rts on (tr.Id = rts.TaskResourceId)
inner join TaskTimeSheets tts on (rts.Id = tts.ResourceTaskScheduleId)
where
((@EmployeeId is null) or (e.Id in (select splitdata from dbo.SplitEmployeeIds(@EmployeeId, ',')))) and
cast(tts.CheckIn as date) >= @StartDate
and cast(tts.CheckIn as date) <= @EndDate
group by
e.Id
ORDER BY
 e.Id
OFFSET (@CurrentPage-1)*@PageSize ROWS
FETCH NEXT @PageSize ROWS ONLY; 

結尾

from子句中使用left join后,通常會繼續使用left join 如果第二個表用於任何條件,這一點至關重要。

然后,任何左連接表上的任何過濾條件都需要在on子句中,而不是where子句中。 所以:

from Employees e left join
     TaskResources tr
     on e.Id = tr.EmployeeId left join
     ResourceTaskSchedules rts
     on tr.Id = rts.TaskResourceId left join
     TaskTimeSheets tts
     on rts.Id = tts.ResourceTaskScheduleId and
        cast(tts.CheckIn as date) >= @StartDate and
        cast(tts.CheckIn as date) <= @EndDate
where ((@EmployeeId is null) or 
       (e.Id in (select splitdata from dbo.SplitEmployeeIds(@EmployeeId, ','))))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM