简体   繁体   中英

Set first week of the year from the first day of the year until the following monday

I want that Oracle treats weeks the following way:

-The week starts on monday
-The first week of the year is from the first day of the year until the following monday

So for 2015 would be

01-jan-2015 (Thursday) would be 1
02-jan-2015 (Friday) would be 1
03-jan-2015 (Saturday) would be 1
04-jan-2015 (Sunday) would be 1
05-jan-2015 (Monday) would be 2
06-jan-2015 (Tuesday) would be 2

For 2017 would be

01-jan-2017 (Sunday) would be 1
02-jan-2017 (Monday) would be 2
03-jan-2017 (Tuesday) would be 2
04-jan-2017 (Wednesday) would be 2

and so on....

I need the numeration for the year so would go to 1 to 53-54

Use the ISO week date standard: 'iw'.

2014-01-01 was Wednesday actually, so:

select
  to_number(to_char(date'2014-01-05', 'iw')) as weeknum, 
  to_char(date'2014-01-05', 'Day') as day
from dual;

    WEEKNUM DAY
----------- ---------
          1 Sunday

select
  to_number(to_char(date'2014-01-06', 'iw')) as weeknum,
  to_char(date'2014-01-06', 'Day') as day
from dual;

    WEEKNUM DAY
----------- ---------
          2 Monday

A little bit of arithmetics will probably do the trick (assuming d is your date):

select TRUNC((case to_char(d, 'DY')
          when 'MON' then 6
          when 'TUE' then 5
          when 'WED' then 4
          when 'THU' then 3
          when 'FRI' then 2
          when 'SAT' then 1
          when 'SUN' then 0
       end + to_number(to_char(d, 'DDD'))-1) / 7)+1
from v;
  • The case statement will build an offset according to the day of week
  • next I add the day of year
  • then I divide the result by 7 for the week number (starting at 0)
  • finally, the +1 will start numbering weeks at 1

Please take some time to experiment with it http://sqlfiddle.com/#!4/d41d8/38236 to check if I didn't make a stupid mistake as I didn't have time to test it thoughtfully. Sorry about that...

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