如何在SQL查询结果中将NULL值替换为0

时间:2010-05-26 06:59:39

标签: sql-server-2005 tsql

SELECT  EmployeeMaster.EmpNo, Sum(LeaveApplications.LeaveDaysTaken) AS LeaveDays
    FROM  EmployeeMaster  FULL OUTER JOIN
    LeaveApplications ON EmployeeMaster.id = LeaveApplications.EmployeeRecordID INNER JOIN
    LeaveMaster ON EmployeeMaster.id = LeaveMaster.EmpRecordID
    GRoup BY EmployeeMaster.EmpNo
    order by LeaveDays Desc

使用上述查询,如果员工在表 LeaveApplications 中没有离开应用程序记录,那么他们的 Sum(LeaveApplications.LeaveDaysTaken)AS LeaveDays 列将返回NULL。我想要做的是将值0(零)而不是NULL。我想这样做,因为我在同一查询中有一个计算列,其公式取决于返回的LeaveDays,当LeaveDays为NULL时,公式表示一些失败。有没有我可以把0为NULL,这样我就可以得到我想要的结果。

3 个答案:

答案 0 :(得分:2)

SELECT  EmployeeMaster.EmpNo, ISNULL(Sum(LeaveApplications.LeaveDaysTaken),0) AS LeaveDays
    FROM  EmployeeMaster  FULL OUTER JOIN
    LeaveApplications ON EmployeeMaster.id = LeaveApplications.EmployeeRecordID INNER JOIN
    LeaveMaster ON EmployeeMaster.id = LeaveMaster.EmpRecordID
    GRoup BY EmployeeMaster.EmpNo
    order by LeaveDays Desc

答案 1 :(得分:1)

您可能想要使用ISNULL

ISNULL(SUM(LeaveApplications.LeaveDaysTaken), 0) AS LeaveDays

答案 2 :(得分:0)

使用isnull功能。