全外连接不起作用

时间:2015-06-03 17:37:19

标签: sql-server

我有一个SQL服务器数据库,我认为我有一个连接问题,但它可能不是一个连接问题。这是一个简单的存储过程

ALTER Proc [dbo].[proc_Time_NotEntered]
(
@sDate datetime,
@eDate datetime
)
AS
BEGIN
    Select (e.[emplname] + ', ' + e.[empfName]) as [FullName],
           wip.wdate as [date],
          Sum(case when wip.wdate between @sDate and @eDate and wip.windicator <> 'D' then wip.[whours] else 0 end) as [Hours],
          dept.[DeptName]

    From sab.dbo.employee as e
    Join sab.dbo.wip as wip on e.[ID] = wip.wempID
    join sab.dbo.department as dept on e.empdept = dept.deptID

    where
        wip.wdate between @sDate and @eDate
        and e.[emplname] + ', ' + e.[empfName] <>  ' No Selection, '
    Group by 
        e.[emplname],
        e.[empfName],
        dept.[DeptName],
        wip.[wdate]
    ORDER BY
    -- wip.[wdate],
     e.[emplname] + ', ' + e.[empfName]
    return 1
END

使用我的加入我尝试了完全外连接并得到相同的结果。

我想要实现的目标:即使每天都没有工作时间,我也希望得到所有员工。

2 个答案:

答案 0 :(得分:1)

您需要左连接才能返回没有匹配的wip记录的员工。

Select e.emplname, wip.wdate 
From sab.dbo.employee as e
Left Join sab.dbo.wip as wip on e.[ID] = wip.wempID and wip.wdate between @sDate and @eDate

答案 1 :(得分:1)

有几件事。首先,JOIN本身就是一个内连接。如果您希望所有员工和其他所有员工都是可选的:

select...
from
employees e
left join wip
on e.[ID] = wip.wempID
and wip.wdate between @sDate and @eDate

您需要将wip上的约束移动到on子句,否则您最终仍会使用内部联接。