圆形负数最多为零

时间:2015-10-08 16:09:39

标签: sql sql-server

我正在尝试创建一个SQL查询,该查询根据出生日期和开始日期返回员工在41岁以上就业的年数。但显然有些员工不满41岁。对于这些我想要归零,但我目前的尝试会返回负数。

如何将负片“舍入”为零?

select EmployeeNo, EmployeeFName, EmployeeLName,
 DATEDIFF(hour,DateOfBirth,GETDATE())/8766 AS Age, 
 DATEDIFF(hour,StartDate,GETDATE())/8766 AS LengthOfService, 
 DATEDIFF(hour,DateOfBirth,GETDATE())/8766 - 41 AS YearsOver41
from Employees

2 个答案:

答案 0 :(得分:2)

CASE WHEN X < 0 THEN 0 ELSE X END

其中X是数字列或表达式,可能是负数。

答案 1 :(得分:1)

select EmployeeNo, EmployeeFName, EmployeeLName,
   DATEDIFF(hour,DateOfBirth,GETDATE())/8766 AS Age, 
   DATEDIFF(hour,StartDate,GETDATE())/8766 AS LengthOfService, 

   CASE 
       WHEN DATEDIFF(hour,DateOfBirth,GETDATE())/8766 - 41) < 0 THEN 0
       ELSE DATEDIFF(hour,DateOfBirth,GETDATE())/8766 - 41 
   END AS YearsOver41

from Employees