簡體   English   中英

是否可以在 oracle 中構建日歷周加上年份之外的日期?

[英]Is it possible to construct a date out of the calendar week plus year in oracle?

我有一個包含日歷周加上年份作為字符串的列,它的構造方式是這樣的

select TO_CHAR(TO_DATE('01.03.2020'),'WW/YYYY') from DUAL

這導致像這樣的字符串

09/2020

是否可以從此字符串重建日期? 我不在乎日期是一周的開始,一周的結束還是本周內的其他任何事情。

WW格式代碼從 1 月 1 日開始計算 7 天周期,因此只需為您的年份獲取 1 月 1 日並添加正確數量的 7 天周期:

甲骨文設置

CREATE TABLE table_name ( value ) AS
  SELECT TO_CHAR( DATE '2020-03-01', 'WW/YYYY' ) FROM DUAL;

查詢

SELECT TO_DATE( SUBSTR( value, 4 ), 'YYYY' ) + ( SUBSTR( value, 1, 2 ) - 1 ) * 7
         AS first_day_of_week,
       TO_DATE( SUBSTR( value, 4 ), 'YYYY' ) + ( SUBSTR( value, 1, 2 ) ) * 7 - 1
         AS last_day_of_week
FROM   table_name

輸出

\n FIRST_DAY_OF_WEEK |  LAST_DAY_OF_WEEK\n :---------------- |  :--------------\n 2020-02-26 |  2020-03-03      \n

db<> 在這里擺弄

像這樣的東西?

with test (col) as
  (select '09/2020' from dual),
-- construct the whole year with week markers 
whole_year as
  (select to_date(substr(col, -4), 'yyyy') + level - 1 datum,
          --
          to_char(to_date(substr(col, -4), 'yyyy') + level - 1, 'ww') week
   from test
   connect by level <= add_months(to_date(substr(col, -4), 'yyyy'), 12) -
                                  to_date(substr(col, -4), 'yyyy')
  )
select min(datum)
from whole_year
where week = '09'; 

whole_year CTE - 第 09 周 - 看起來像這樣:

DATUM      WE
---------- --
25.02.2020 08
26.02.2020 09        --> this
27.02.2020 09
28.02.2020 09
29.02.2020 09
01.03.2020 09
02.03.2020 09
03.03.2020 09
04.03.2020 10
05.03.2020 10
06.03.2020 10

這意味着我在上面發布的查詢結果返回

 <snip>
 12  select min(datum)
 13  from whole_year
 14  where week = '09';

MIN(DATUM)
----------
26.02.2020

SQL>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM