一尘不染

如何使用Oracle获得年龄,月份和天数的年龄

sql

我正在尝试使用以下格式为每个人打印其年龄:

例如:19年8个月13天。

我已经在Google上搜索了很多,并且注意到有一个特定的函数可以计算日期之间的差DATEDIFF

但是,该功能在中不存在SQL*Plus,因此我继续尝试使用MONTHS_BETWEEN()和一些运算符。

我的尝试:

SELECT name , ' ' || 
    FLOOR(MONTHS_BETWEEN(to_date(SYSDATE),to_date(date_of_birth))/12)||' years ' ||  
    FLOOR(MOD(MONTHS_BETWEEN(to_date(SYSDATE),to_date(date_of_birth)),12)) || ' months ' || 
    FLOOR(MOD(MOD(MONTHS_BETWEEN(to_date(SYSDATE),to_date(date_of_birth)),12),4))|| ' days ' AS "Age"
FROM persons;

我的问题取决于日子。我不知道如何使用此函数计算天数(“尝试除以4或30”);我以为我的逻辑不好,但我无法弄清楚,有什么想法吗?


阅读 285

收藏
2021-03-10

共1个答案

一尘不染

与Lalit的答案非常相似,但是您可以add_months通过按整个月的总差异进行调整来获得准确的天数,而无需假设每月有30天:

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

您可以通过反转计算来验证:

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
2021-03-10