Calculate exact date difference in years using SQL

后端 未结 4 1968
走了就别回头了
走了就别回头了 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:34

    I have found a better solution. This makes the assumption that the first date is less than or equal to the second date.

    declare @dateTable table (date1 datetime, date2 datetime)
    insert into @dateTable 
        select '2017-12-31', '2018-01-02' union
        select '2017-01-03', '2018-01-02' union 
        select '2017-01-02', '2018-01-02' union
        select '2017-01-01', '2018-01-02' union
        select '2016-12-01', '2018-01-02' union
        select '2016-01-03', '2018-01-02' union
        select '2016-01-02', '2018-01-02' union
        select '2016-01-01', '2018-01-02' 
    select date1, date2, 
            case when ((DATEPART(year, date1) < DATEPART(year, date2)) and 
                        ((DATEPART(month, date1) <= DATEPART(month, date2)) and 
    (DATEPART(day, date1) <= DATEPART(day, date2)) ))
                        then DATEDIFF(year, date1, date2)
                when (DATEPART(year, date1) < DATEPART(year, date2))
                        then DATEDIFF(year, date1, date2) - 1
                when (DATEPART(year, date1) = DATEPART(year, date2))
                        then 0
            end [YearsOfService]
    from @dateTable
    
    date1                   date2                   YearsOfService
    ----------------------- ----------------------- --------------
    2016-01-01 00:00:00.000 2018-01-02 00:00:00.000 2
    2016-01-02 00:00:00.000 2018-01-02 00:00:00.000 2
    2016-01-03 00:00:00.000 2018-01-02 00:00:00.000 1
    2016-12-01 00:00:00.000 2018-01-02 00:00:00.000 1
    2017-01-01 00:00:00.000 2018-01-02 00:00:00.000 1
    2017-01-02 00:00:00.000 2018-01-02 00:00:00.000 1
    2017-01-03 00:00:00.000 2018-01-02 00:00:00.000 0
    2017-12-31 00:00:00.000 2018-01-02 00:00:00.000 0
    

提交回复
热议问题