首页 > 解决方案 > 如何在sql查询oracle中获取两个月之间的年份以及月份和日期

问题描述

我需要提取两个月之间的年数、月数,例如我的输出看起来像1year 9months. 我不知道如何显示这样的输出,下面是我现在使用的查询。

select round((MONTHS_BETWEEN(lease_end_date,lease_start_date)/12),1) Duration_In_Years
from lease_header

标签: sqloracle

解决方案


这样的事情怎么样?阅读代码中的注释:

SQL> with test (date_1, date_2) as
  2    -- sample dates; to test the query, modify these values
  3    (select date '2021-10-20', date '2020-09-01' from dual),
  4  temp as
  5    -- split result of MONTHS_BETWEEN to number of years and number of months
  6    (select
  7       trunc(months_between(date_1, date_2) / 12) yrs,
  8       round((months_between(date_1, date_2) / 12 - trunc(months_between(date_1, date_2) / 12)) * 12, 1) mon
  9     from test
 10    )
 11  -- final result
 12  select yrs || ' year(s) ' || mon || ' month(s)' result
 13  from temp;

RESULT
----------------------
1 year(s) 1,6 month(s)

SQL>

推荐阅读