how to get the number on months between two dates in sql server 2005

前端 未结 4 1765
余生分开走
余生分开走 2021-01-13 08:49

I have a column in my sql server 2005 table that should hold the number of months an employee has been in service.

Since I also have the date the employee was engage

相关标签:
4条回答
  • 2021-01-13 09:18

    If You presume that month is meaning for 30 days You can also round vale

    round((datediff(day,[DateEngaged],getdate()))/30.00,0)
    
    0 讨论(0)
  • 2021-01-13 09:22

    Maybe you want something like:

    (year(getdate())-year([DateEngaged]))*12+(month(getdate())-month([DateEngaged]))
    
    0 讨论(0)
  • 2021-01-13 09:32

    Something like (might need to swap the 1 and 0, untested)

    datediff(month,[DateEngaged],getdate()) +
     CASE WHEN DATEPART(day, [DateEngaged]) < DATEPART(day, getdate()) THEN 1 ELSE 0 END
    

    DATEDIFF measure month boundaries eg 00:00 time on 1st of each month, not day-of-month anniversaries

    Edit: after seeing OP's comment, you have to subtract 1 if the start day > end day

    DATEDIFF (month, DateEngaged, getdate()) -
     CASE
       WHEN DATEPART(day, DateEngaged) > DATEPART(day, getdate()) THEN 1 ELSE 0
     END
    

    So for 20 Dec to 13 Jan, DATEDIFF gives 1 and then 20 > 13 so subtract 1 = zero months.

    0 讨论(0)
  • 2021-01-13 09:34

    Same approach as gbn, but with less keystrokes :-)

    SELECT 
        DATEDIFF(MONTH, DateEngaged, GETDATE()) +
        CASE 
            WHEN DAY(DateEngaged) < DAY(GETDATE())
            THEN 1 
            ELSE 0 
        END
    
    0 讨论(0)
提交回复
热议问题