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

标签 sql oracle date-arithmetic

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

例如: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”);我以为我的逻辑不好,但我无法弄清楚,有什么想法吗?

最佳答案

与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

关于sql - 如何使用Oracle获得年龄,月份和天数的年龄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33343596/

相关文章:

php - OR AND 的 Mysql 错误

php - Sql从字符串中选择数据选择id

mysql - 类名错误或未设置 : com. mysql.jdbc.Driver 的类路径

sql - Oracle SQL Developer 中的周转时间计算

php - 如何将 PHP 中的分钟转换为小时和分钟以及负分钟?

sql - 基于多行SQL过滤数据

oracle - Hibernate 2.1.7 可以与 Oracle Database 11gR2 一起使用吗?

Python,Oracle DB,一列中的XML数据,获取cx_Oracle.Object

SQL:计算不同行中一列日期之间的天数

mysql - 如何查询日期并在结果中添加3天?