How to use DATEDIFF to return year, month and day?

后端 未结 9 918
离开以前
离开以前 2020-12-10 22:36

How can I use DATEDIFF to return the difference between two dates in years, months and days in SQL Server 2005

DATEDIFF (date , dat         


        
9条回答
  •  再見小時候
    2020-12-10 23:33

    TL;DR approximates years & months without having to create a function.


    I found this question searching for "get years months from datediff". I was looking for something a bit quicker (and yeah, probably dirtier) than the above function-creating solutions.

    I came up with the following in-line sql which approximates the years and months. Sufficient for my own purposes, which is getting a count of events grouped by user's rough age at the time.

    select cast(datediff(event_datetime, dateofbirth)/365.25 as unsigned) as years, 
           cast((mod(datediff(event_datetime, dateofbirth),365.25))/30.4375 as unsigned) as months
    from tablename
    ;
    

提交回复
热议问题