SQL计算问题

时间:2016-12-30 16:41:24

标签: sql sql-server

我有以下任务:

  

显示年龄的员工的姓名和年龄列表   大于55.结果应按姓氏排序。

这是我的代码:

SELECT 
    LastName, FirstName,  
    (CASE 
        WHEN (CONVERT(INT, GETDATE()) - CONVERT(INT, BirthDate)) > 55 
           THEN CONVERT(INT, GETDATE()) - CONVERT(INT, BirthDate) 
     END) as Age 
FROM 
    Employees  
ORDER BY 
    LastName

这就是我得到的:

enter image description here

这是BirthDate表(日期时间):

enter image description here

为什么年龄这么疯狂?怎么了?

4 个答案:

答案 0 :(得分:1)

对于年龄,请使用表达式

 DateDiff(year, birthdate, getdate()) +
    case when Month(getdate()) > Month(birthdate) 
           or Day(getdate()) >= Day(birthdate) 
       then 1 else 0 end

即,

SELECT LastName, FirstName,  
    DateDiff(year, birthdate, getdate()) +
    case when Month(getdate()) > Month(birthdate) 
           or Day(getdate()) >= Day(birthdate) 
       then 1 else 0 end Age 
FROM Employees  
where DateDiff(year, birthdate, getdate()) +
    case when Month(getdate()) > Month(birthdate) 
           or Day(getdate()) >= Day(birthdate) 
       then 1 else 0 end > 55
ORDER BY LastName

答案 1 :(得分:0)

 SELECT * 
 FROM
     (SELECT 
          LastName, FirstName,  
          (CASE 
              WHEN DATEDIFF(yy, BirthDate, GETDATE()) > 55 
                 THEN DATEDIFF(yy, BirthDate, GETDATE()) 
                 ELSE 0 
            END) AS Age 
      FROM 
          Employees) AS ABC
WHERE 
    ABC.Age != 0
ORDER BY 
    ABC.LastName

答案 2 :(得分:0)

您的结果中的问题是您将日期转换为int并且您未将Int转换回Date

Where子句中添加过滤器。要计算年龄,我总是使用以下方法

SELECT FLOOR(DATEDIFF(DAY, '1990-07-20', getdate()) / 365.25)

结果:26

SELECT LastName,
       FirstName,
       Floor(Datediff(DAY, BirthDate, Getdate()) / 365.25) AS Age
FROM   Employees
WHERE  Floor(Datediff(DAY, BirthDate, Getdate()) / 365.25) > 55
ORDER  BY LastName 

答案 3 :(得分:0)

我强烈建议您使用datediff()。它不直观。它计算两个日期之间的年份边界数。虽然新年庆祝活动与年龄之间存在关系,但这两者并不相同。

相反:

SELECT LastName, FirstName
FROM Employees  
WHERE birthdate < DATEADD(year, -55, getdate())
ORDER BY LastName;

不幸的是,这并没有达到这个年龄。这有点棘手。你可以使用datediff()只是为了足够接近&#34;。确切的逻辑是有点痛苦。我会推荐你​​here