如何在 Oracle 中获取两个日期之间的差异并将其显示为' x years y month z days'



我需要计算Oracle sql中两个日期之间的差异,并以以下格式显示:"x年y月z天"。

现在我看到了实现这一目标的两种方法:

第一种方法是获得天数的差异,然后将其调整为"x年y月z天"

第二种方法是使用提取函数提取年、月和天。

在第一种和第二种情况下,我看到了如何处理闰年和30天与31天的月份差异的问题。

有没有其他更简单的方法来实现这一点?

作为另一个选项,您可以使用months_between()函数,并将提供给您的值分为三部分。例如,对于一些样本日期:

select months_between(date '2015-03-19', date '2012-01-06') as month_diff
from dual;
MONTH_DIFF
----------
38.4193548

整个月的数量可以分为十二(即年)的三倍,剩下两个;小数部分是基于31天的月份的部分月份中的天数。

因此,您可以使用提取零件

with t (start_date, end_date) as (
  select date '2012-01-06', date '2015-03-19' from dual
)
select start_date, end_date,
  trunc(month_diff/12) as year_diff,
  trunc(mod(month_diff, 12)) as month_diff,
  31*(month_diff - trunc(month_diff)) as day_diff
from (
  select start_date, end_date,
    months_between(end_date, start_date) as month_diff
  from t
);
START_DATE END_DATE    YEAR_DIFF MONTH_DIFF   DAY_DIFF
---------- ---------- ---------- ---------- ----------
2012-01-06 2015-03-19          3          2         13

然后你可以使用字符串串联来格式化它,无论你想要什么,例如

select trunc(month_diff/12) || ' years '
  || trunc(mod(month_diff, 12)) || ' months '
  || 31*(month_diff - trunc(month_diff)) || ' days' as diff
from (
...
DIFF                   
------------------------
3 years 2 months 13 days

我刚刚使用了这个公式,并添加了一些情况,其中两个日期之间的间隔为1天将导致2天的差异。

  • 案例1:2019年4月8日至2021年4月30日->2年零22天
  • 病例2:2019年4月8日至2021年5月1日(多一天)->2年零24天(2天以上)

我已经更正了公式:

 with t (start_date, end_date) as (
  select date '2012-01-06', date '2015-03-19' from dual
)
select start_date, end_date,
  trunc(month_diff/12) as year_diff,
  trunc(mod(month_diff, 12)) as month_diff,
end_date - add_months(start_date, month_diff) as day_diff
from (
  select start_date, end_date,
    trunc(months_between(end_date, start_date)) as month_diff
  from t
);
Try 
SELECT months_between('27-Mar-2021','28-Feb-2021') from dual; Output 9.66
SELECT months_between('28-Mar-2021','28-Feb-2021') from dual; Output 1.0
SELECT months_between('29-Mar-2021','28-Feb-2021') from dual; Output 1.03 
SELECT months_between('31-Mar-2021','28-Feb-2021') from dual; Output 1.0
select e.emp_code,e.emp_name,
        e.emp_dob,
       trunc(months_between(trunc(sysdate),e.emp_dob) / 12) || ' Yrs ' ||
        trunc(mod(months_between(trunc(sysdate),e.emp_dob ),12)) || 'Mon. ' ||
        (trunc(sysdate) - add_months(e.emp_dob,trunc(months_between(trunc(sysdate),e.emp_dob)))) ||'Dys. ' age
  from  employee e
  WHERE e.emp_date_left IS NULL
  ORDER BY 1;

我从这个查询中得到了正确的答案

相关内容