简体   繁体   中英

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:

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 |  LAST_DAY_OF_WEEK \n:---------------- |  :--------------- \n2020-02-26 |  2020-03-03       \n

db<>fiddle here

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:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM