把日子变成几周,几个月,几年.ORACLE

时间:2013-11-23 00:50:37

标签: sql database oracle11g

我有这个查询和结果:

SQL> select AVG(SYSDATE - DOB) AS AVERAGE_AGE_IN_DAYS
  2  FROM MORTAL;

AVERAGE_AGE_IN_DAYS
-------------------
           17877.44

有没有办法在同一个查询中将其转换为年,月和日?

3 个答案:

答案 0 :(得分:2)

获取可以使用months_between

的月数
SELECT select AVG(months_between(SYSDATE,DOB)) AS AVERAGE_AGE_IN_MONTHS

多年来,只需做几个月/ 12个

SELECT select AVG(months_between(SYSDATE,DOB)/12) AS AVERAGE_AGE_IN_YEARS

几个星期以来,我只会把你的结果用了几天,除以7。

您可能必须处理结果以满足您的需求,但我认为这应该涵盖它。

答案 1 :(得分:2)

怎么样:

select 
floor(months_between(SYSDATE,DOB)/12) AS years,
trunc( months_between(SYSDATE,DOB) ) AS months, 
SYSDATE - add_months( SYSDATE, trunc(months_between(SYSDATE,DOB)) ) AS days

详细信息表明这是几年,几个月,几天。标题也说了几周,但如果你真的想要它们,我就不会。

答案 2 :(得分:0)

也许您的查询是:

with dates as (select AVG(SYSDATE - DOB) as d --average_in_days
                 from MORTAL
              )
select trunc(d/365) as years
     , trunc((d/365 - trunc(d/365)) * 12 ) as months
     , trunc((((d/365 - trunc(d/365)) * 12) - trunc((d/365 - trunc(d/365)) * 12 )) * 4.348214) as weeks     
     , trunc(((((d/365 - trunc(d/365)) * 12) - trunc((d/365 - trunc(d/365)) * 12 )) * 4.348214
                       - trunc((((d/365 - trunc(d/365)) * 12) - trunc((d/365 - trunc(d/365)) * 12 )) * 4.348214 )
             ) * 7 
             ) as days     
from dates;