SQL Server,如果Null = 0

时间:2018-01-07 16:39:34

标签: sql sql-server database

如何显示NULL值= 0

SELECT
    d.Date,
    a.EmployeeID,
    a.GivenName, a.FamilyName,
    a.TeamID,
    d.ShiftType, d.ShiftDuration,
    b.Duration_Off,
    c.OT_Duration,
    (d.ShiftDuration + c.OT_Duration) - b.Duration_Off as Total_Hours
FROM 
    Employee a
INNER JOIN 
    Roster d ON  a.EmployeeID = d.EmployeeID 
LEFT JOIN 
    Leave b ON a.EmployeeID = b.EmployeeID 
LEFT JOIN 
    Overtime c ON  a.EmployeeID = c.EmployeeID 

Result of query when ran.

由于我的Duration_OffOT_Duration有时可能NULL,如何在0时显示NULL

1 个答案:

答案 0 :(得分:1)

使用coalesce()

select . . .,
       coalesce(d.ShiftDuration, 0) as ShiftDuration,
       coalesce(b.Duration_Off, 0) as Duration_Off,
       coalesce(c.OT_Duration, 0) as OT_Duration
       (coalesce(d.ShiftDuration, 0) + coalesce(c.OT_Duration, 0) - coalesce(b.Duration_Off, 0)
       ) as Total_Hours

为了使算法正常工作,coalesce()总和的每个分量都需要Total_Hours