How to get age in years,months and days using Oracle

前端 未结 4 1774
-上瘾入骨i
-上瘾入骨i 2020-12-17 03:53

I\'m trying to print for each person its age using this format :

E.g : 19 years , 8 months , 13 days.

I\'ve googled a lot and I\'ve noticed that there is a s

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-17 04:11

    Very similar to Lalit's answer, but you can get an accurate number of days without assuming 30 days per month, by using add_months to adjust by the total whole-month difference:

    select sysdate,
      hiredate,
      trunc(months_between(sysdate,hiredate) / 12) as years,
      trunc(months_between(sysdate,hiredate) -
        (trunc(months_between(sysdate,hiredate) / 12) * 12)) as months,
      trunc(sysdate)
        - add_months(hiredate, trunc(months_between(sysdate,hiredate))) as days
    from emp;
    
    SYSDATE    HIREDATE        YEARS     MONTHS       DAYS
    ---------- ---------- ---------- ---------- ----------
    2015-10-26 1980-12-17         34         10          9
    2015-10-26 1981-02-20         34          8          6
    2015-10-26 1981-02-22         34          8          4
    2015-10-26 1981-04-02         34          6         24
    2015-10-26 1981-09-28         34          0         28
    2015-10-26 1981-05-01         34          5         25
    2015-10-26 1981-06-09         34          4         17
    2015-10-26 1982-12-09         32         10         17
    2015-10-26 1981-11-17         33         11          9
    2015-10-26 1981-09-08         34          1         18
    2015-10-26 1983-01-12         32          9         14
    2015-10-26 1981-12-03         33         10         23
    2015-10-26 1981-12-03         33         10         23
    2015-10-26 1982-01-23         33          9          3
    

    You can verify by reversing the calculation:

    with tmp as (
        select trunc(sysdate) as today,
          hiredate,
          trunc(months_between(sysdate,hiredate) / 12) as years,
          trunc(months_between(sysdate,hiredate) -
            (trunc(months_between(sysdate,hiredate) / 12) * 12)) as months,
          trunc(sysdate)
            - add_months(hiredate, trunc(months_between(sysdate,hiredate))) as days
        from emp
    )
    select * from tmp
    where today != add_months(hiredate, (12 * years) + months) + days;
    
    no rows selected
    

提交回复
热议问题