在整数字段上计算年龄

时间:2019-09-24 19:43:12

标签: sql sql-server tsql

我要计算年龄的日期字段是yyyymmdd

我在下面进行了尝试,并将getdate转换为yyyymmdd格式,但似乎无法确定年龄。我尝试使用datediff,但似乎也无法使其正常工作。

 SELECT CLAIM.BTHDAT
     , (CONVERT(VARCHAR(8),GETDATE(), 112) - CLAIM.BTHDAT)/365.25   
 FROM CLAIM

3 个答案:

答案 0 :(得分:1)

假设您希望在AGE年内... datediff()

Select Age = datediff(YEAR,left(CLAIM.BTHDAT,8),getdate())
 From  CLAIM

答案 1 :(得分:0)

尝试一下。...

SELECT CLAIM.BTHDAT, DATEDIFF(hour,CLAIM.BTHDAT,GETDATE())/8766.0 AS AgeYearsDecimal
    ,CONVERT(int,ROUND(DATEDIFF(hour,CLAIM.BTHDAT,GETDATE())/8766.0,0)) AS AgeYearsIntRound
    ,DATEDIFF(hour,CLAIM.BTHDAT,GETDATE())/8766 AS AgeYearsIntTrunc  FROM CLAIM

如果要按日,月和年进行年龄划分,则可以尝试此操作。创建函数以计算年龄并按如下所示在查询中调用

    Create function [dbo].[GetAge](@dayOfBirth datetime, @today datetime)
       RETURNS varchar(100)
    AS

    Begin
      DECLARE @tmpdate datetime, @date datetime, @years int, @months int, @days int

    SELECT @tmpdate = @dayOfBirth

    SELECT @years = DATEDIFF(yy, @tmpdate, @today) - CASE WHEN (MONTH(@tmpdate) > MONTH(@today)) OR (MONTH(@tmpdate) = MONTH(@today) AND DAY(@tmpdate) > DAY(@today)) THEN 1 ELSE 0 END
    SELECT @tmpdate = DATEADD(yy, @years, @tmpdate)
    SELECT @months = DATEDIFF(m, @tmpdate, @today) - CASE WHEN DAY(@tmpdate) > DAY(@today) THEN 1 ELSE 0 END
    SELECT @tmpdate = DATEADD(m, @months, @tmpdate)
    SELECT @days = DATEDIFF(d, @tmpdate, @today)

    return cast(@years as varchar(2)) + ' years,' + cast(@months as varchar(2)) + ' months,' + cast(@days as varchar(3)) + ' days'
    end


Select  CLAIM.BTHDAT,dbo.[GetAge](CLAIM.BTHDAT,getdate()) From CLAIM

答案 2 :(得分:0)

这里有一个选项,可以假设所有日期都遵循yyyymmdd格式并且是有效日期,从而可以准确地获得年龄。

SELECT CLAIM.BTHDAT
 ,DATEDIFF( YY, CONVERT(CHAR(8),CLAIM.BTHDAT), GETDATE()) 
   - CASE WHEN SUBSTRING( CONVERT( char(8), GETDATE(), 112), 5, 4) < SUBSTRING( CONVERT( char(8), BTHDAT), 5, 4)  THEN 1 ELSE 0 END
 FROM CLAIM