简体   繁体   English

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

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

I have a column containing calendar weeks plus year as string, which was constructed in way like this我有一个包含日历周加上年份作为字符串的列,它的构造方式是这样的

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

which results in a string like这导致像这样的字符串

09/2020

Is it possible to reconstruct the date from this string?是否可以从此字符串重建日期? I would not care if the date is start of the week, end of the week or anything else within this week.我不在乎日期是一周的开始,一周的结束还是本周内的其他任何事情。

The WW format code counts 7-day periods starting at 1st January so just get 1st January for your year and add the correct number of 7-day periods: WW格式代码从 1 月 1 日开始计算 7 天周期,因此只需为您的年份获取 1 月 1 日并添加正确数量的 7 天周期:

Oracle Setup :甲骨文设置

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

Query :查询

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

Output :输出

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

db<>fiddle here db<> 在这里摆弄

Something like this?像这样的东西?

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'; 

The whole_year CTE - for week 09 - looks like this: 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

which means that query I posted above, as a result, returns这意味着我在上面发布的查询结果返回

 <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