Oracle 將天數(1-366)轉換為日期

來源:互聯網
上載者:User

//在平時的應用中,我們很多地方都使用了日期函數to_date()  
//但是我們對日期函數的格式知道得很少,或者說我們根本就不會去研究它  
//然而,知道日期格式是多麼的重要  
//下面是一個具體的應用:  
//有一張表,有年欄位year,時期欄位type,期數term,如下  
ID  year  type  term  
---------------------  
1   2010   R     1  
2   2010   R     2  
. . . .  
. . . .  
N   2010   R    365  
//結果:  
id   year  type  term  
----------------------  
1   2010    R   2010-01-01  
. . . .  
. . . .   
N   2010    R   2010-12-31  
//分析:  
//這是將天數轉換為日期,我們平時接觸到的基本上都是字串的日期轉換為日期格式,  
//這還是將天數轉換為日期,確實有點困難;  
//不過,好在Oracle人員在設計to_date函數時已經考慮到了這個問題,  
//所以我們不必要擔心,查詢一下to_date函數的format格式,  
//發現一個format參數表示將在[1-366]區間的數轉換為日期的格式:  
//DDD   Day of year (1-366).  
//下面是具體的解法:  
with t as(  
     select 1 id,'2000' year, 'R' type, 1 term from dual union all   
     select 2,'2000', 'R', 58 from dual union all   
     select 3,'2010', 'R', 59 from dual union all   
     select 4,'2010', 'R', 60 from dual union all   
     select 5,'2011', 'R', 128 from dual union all   
     select 6,'2011', 'R', 129 from dual union all   
     select 7,'2001', 'R', 130 from dual union all   
     select 8,'2005', 'R', 365 from dual union all   
     select 9,'2008', 'R', 366 from dual)  
select id,  
       year,  
       type,  
       term,  
       to_char(to_date(year||term,'yyyyddd'),'yyyy-mm-dd') ymd  
from t;  
        ID YEAR TYPE       TERM YMD  
---------- ---- ---- ---------- ----------  
         1 2000 R             1 2000-01-01  
         2 2000 R            58 2000-02-27  
         3 2010 R            59 2010-02-28  
         4 2010 R            60 2010-03-01  
         5 2011 R           128 2011-05-08  
         6 2011 R           129 2011-05-09  
         7 2001 R           130 2001-05-10  
         8 2005 R           365 2005-12-31  
         9 2008 R           366 2008-12-31 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.