Get the difference between two dates both In Months and days in sql

后端 未结 10 1979
萌比男神i
萌比男神i 2020-12-31 07:43

I need to get the difference between two dates say if the difference is 84 days, I should probably have output as 2 months and 14 days, the code I have just gives the totals

10条回答
  •  执念已碎
    2020-12-31 07:59

    select 
      dt1, dt2,
      trunc( months_between(dt2,dt1) ) mths, 
      dt2 - add_months( dt1, trunc(months_between(dt2,dt1)) ) days
    from
    (
        select date '2012-01-01' dt1, date '2012-03-25' dt2 from dual union all
        select date '2012-01-01' dt1, date '2013-01-01' dt2 from dual union all
        select date '2012-01-01' dt1, date '2012-01-01' dt2 from dual union all
        select date '2012-02-28' dt1, date '2012-03-01' dt2 from dual union all
        select date '2013-02-28' dt1, date '2013-03-01' dt2 from dual union all
        select date '2013-02-28' dt1, date '2013-04-01' dt2 from dual union all
        select trunc(sysdate-1)  dt1, sysdate               from dual
    ) sample_data
    

    Results:

    |                        DT1 |                       DT2 | MTHS |     DAYS |
    ----------------------------------------------------------------------------
    |  January, 01 2012 00:00:00 |   March, 25 2012 00:00:00 |    2 |       24 |
    |  January, 01 2012 00:00:00 | January, 01 2013 00:00:00 |   12 |        0 |
    |  January, 01 2012 00:00:00 | January, 01 2012 00:00:00 |    0 |        0 |
    | February, 28 2012 00:00:00 |   March, 01 2012 00:00:00 |    0 |        2 |
    | February, 28 2013 00:00:00 |   March, 01 2013 00:00:00 |    0 |        1 |
    | February, 28 2013 00:00:00 |   April, 01 2013 00:00:00 |    1 |        1 |
    |   August, 14 2013 00:00:00 |  August, 15 2013 05:47:26 |    0 | 1.241273 |
    

    Link to test: SQLFiddle

提交回复
热议问题