T-SQL: calculate age then add character to result

前端 未结 3 1554
轮回少年
轮回少年 2021-01-14 04:47

Been stuck on this one for a while now. Let\'s say I have a Client table like the one here:

Name   BirthDayNum   BirthMonthNum   BirthYearNum
--         


        
3条回答
  •  忘掉有多难
    2021-01-14 05:39

    If you are on 2008 or lesser and can't use datefromparts...

    declare @table table ([Name] varchar(4), BirthDayNum int, BirthMonthNum int, BirthYearNum int)
    insert into @table
    values
    ('John',23,12,1965),
    ('Jane',4,9,1975),
    ('Day',30,3,1990)
    
    ;with cte as(
        select
            [Name],
            cast(BirthYearNum as varchar(4)) + '/' + cast(BirthMonthNum as varchar(2)) + '/' + cast(BirthDayNum as varchar(2)) as DOB
        from 
            @table)
    
    select 
         [Name]
         ,DOB
         ,datediff(year,DOB,GETDATE()) as Years
         ,datediff(month,DOB,GETDATE()) %12 as Months
         ,rtrim(cast(datediff(year,DOB,GETDATE()) as char(2))) + 'y ' + rtrim(cast(datediff(month,DOB,GETDATE()) %12 as char(2))) + 'm' as  Age 
    from cte
    

提交回复
热议问题