将天数转换为年、月和日

问题描述 投票:0回答:1

我有一个 Oracle 表,显示某项已保留的天数:

项目ID 预留天数
100 254
101 4325
102 1355
等等

我想使用 SQL 将天数转换为年、月和日:

项目ID 预留天数 预约期限
100 254 0年8个月10天
101 4325 11年10个月3天
102 1355 3年8个月16天
等等

我发现了很多在 Excel 和其他语言中执行此操作的方法,但没有关于如何在 Oracle SQL 中执行此操作的示例。

sql oracle
1个回答
0
投票

你可以使用这样的东西:

with YrTbl as (
  select 100 as ItemId, 254 as DaysReserved from dual union all
  select 101 as ItemId, 4325 as DaysReserved from dual union all
  select 102 as ItemId, 1355 as DaysReserved from dual 
  ),
FindParts as (
  select ItemID
       , trunc(DaysReserved/365.2425) as Yrs
       , trunc((DaysReserved
            -trunc(DaysReserved/365.2425)*365.2425)/30.44) as Months
       , trunc(DaysReserved
            - trunc(DaysReserved/365.2425)*365.2425
            - trunc((DaysReserved
                -trunc(DaysReserved/365.2425)*365.2425)/30.44)*30.44) as Days
  from YrTbl
  )
select ItemID
     , to_char(Yrs) || ' Years, ' 
       || to_char(Months)|| ' Months, ' 
       || to_char(Days) || ' Days' as ReservationPeriod
from FindParts

但是,我有一种感觉,你已经考虑过类似的事情并正在寻找一些“神奇”的东西??

顺便说一句:365.2425 是公历一年中的平均天数,30.44 是月中的平均天数。

© www.soinside.com 2019 - 2024. All rights reserved.