How to calculate difference between two dates in months in MySQL

前端 未结 7 1598
眼角桃花
眼角桃花 2020-12-13 15:58

I have two columns in a MySQL table:

  • DateOfService (datetime)
  • BirthDate (date)

I want to run a MySQL query that will provide date diffe

7条回答
  •  抹茶落季
    2020-12-13 16:50

    Based on a summary of all answers and a Google search, I think there are four almost similar ways to write it:

    1)

    TIMESTAMPDIFF(MONTH, Start_date, End_date) AS Period
    

    E.g.

    TIMESTAMPDIFF(MONTH, MIN(r.rental_date), MAX(r.rental_date)) AS Period
    

    2)

    PERIOD_DIFF(date_format(now(), '%Y%m'), date_format(time, '%Y%m')) as months
    

    Or

    PERIOD_DIFF(date_format(End_date(), '%Y%m'), date_format(Start_date, '%Y%m')) as months
    

    E.g.

    PERIOD_DIFF(date_format(MAX(r.rental_date), '%Y%m'), date_format(MIN(r.rental_date), '%Y%m')) as months
    

    3)

    PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM NOW()), EXTRACT(YEAR_MONTH FROM time)) AS months
    

    OR

    PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM End_date()), EXTRACT(YEAR_MONTH FROM Start_date)) AS months
    

    E.g.

    PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM MAX(r.rental_date)), EXTRACT(YEAR_MONTH FROM MIN(r.rental_date))) as Months
    

    4)

    PERIOD_DIFF(concat(year(d1),if(month(d1)<10,'0',''),month(d1)), concat(year(d2),if(month(d2)<10,'0',''),month(d2))) as Months**
    

    E.g.

    PERIOD_DIFF(
                concat(year(MAX(r.rental_date)),if(month(MAX(r.rental_date))<10,'0',''),month(MAX(r.rental_date))),
                concat(year(MIN(r.rental_date)),if(month(MIN(r.rental_date))<10,'0',''),month(MIN(r.rental_date)))
               ) as Months
    

提交回复
热议问题