繁体   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