Calculate exact date difference in years using SQL

后端 未结 4 1957
走了就别回头了
走了就别回头了 2020-12-11 02:17

I receive reports in which the data is ETL to the DB automatically. I extract and transform some of that data to load it somewhere else. One thing I need to d

4条回答
  •  春和景丽
    2020-12-11 02:59

    Have you tried getting the difference in months instead and then calculating the years that way? For example 30 months / 12 would be 2.5 years.

    Edit: This SQL query contains several approaches to calculate the date difference:

    SELECT CONVERT(date, GetDate() - 912) AS calcDate
          ,DATEDIFF(DAY, GetDate() - 912, GetDate()) diffDays
          ,DATEDIFF(DAY, GetDate() - 912, GetDate()) / 365.0 diffDaysCalc
          ,DATEDIFF(MONTH, GetDate() - 912, GetDate()) diffMonths
          ,DATEDIFF(MONTH, GetDate() - 912, GetDate()) / 12.0 diffMonthsCalc
          ,DATEDIFF(YEAR, GetDate() - 912, GetDate()) diffYears
    

提交回复
热议问题