简体   繁体   中英

Calculate manual week number of year in Oracle SQL

i have a date column and along that i need to calculate another column in oracle for week number of they year, the weeks should be from sunday to saturday, starting first day of the year.

for example for current year

Week 1 : 1 Jan 2020 (Wednesday) - 4 Jan 2020(Saturday)


Week 2 : 5 Jan 2020 (Sunday)        - 11 Jan 2020(Saturday)

. . . . .


Week 5 : 26 Jan 2020 (Sunday) - 1 Feb 2020 (Saturday)

and so on...

You need to write your own logic using a hierarchy query .

Something like the following:

 SQL> SELECT WEEKNUMBER, 2 WEEK_START, 3 CASE WHEN WEEKNUMBER = 1 THEN FIRST_WEEKEND ELSE WEEK_START + 6 END AS WEEK_END 4 FROM 5 (SELECT 6 CASE 7 WHEN LEVEL = 1 THEN FIRST_DAY 8 ELSE FIRST_WEEKEND + ( LEVEL - 2 ) * 7 + 1 9 END AS WEEK_START, 10 FIRST_WEEKEND, 11 LEVEL AS WEEKNUMBER 12 FROM 13 ( SELECT 14 TRUNC(SYSDATE, 'YEAR') FIRST_DAY, 15 NEXT_DAY(TRUNC(SYSDATE, 'YEAR'), 'SATURDAY') FIRST_WEEKEND 16 FROM DUAL ) 17 CONNECT BY 18 CASE WHEN LEVEL = 1 THEN FIRST_DAY 19 ELSE FIRST_WEEKEND + ( LEVEL - 2 ) * 7 + 1 20 END < ADD_MONTHS(TRUNC(SYSDATE, 'YEAR'), 12)); WEEKNUMBER WEEK_STAR WEEK_END ---------- --------- --------- 1 01-JAN-20 04-JAN-20 2 05-JAN-20 11-JAN-20 3 12-JAN-20 18-JAN-20 4 19-JAN-20 25-JAN-20 5 26-JAN-20 01-FEB-20 6 02-FEB-20 08-FEB-20 7 09-FEB-20 15-FEB-20 8 16-FEB-20 22-FEB-20 9 23-FEB-20 29-FEB-20 10 01-MAR-20 07-MAR-20 11 08-MAR-20 14-MAR-20 ....... ....... 53 27-DEC-20 02-JAN-21

Cheers!!

One other option would be

with t as
(
 select trunc(sysdate,'yyyy')+level-1 as day, to_char(trunc(sysdate,'yyyy')+level-1,'DY','NLS_DATE_LANGUAGE=AMERICAN') as weekday, level - 1 as lvl
   from dual
 connect by level <= 366
), t1 as
(
select case
         when lvl = 0 then
          day
         else
          case
            when weekday = 'SUN' then
             day
          end
       end as day1,       
       lvl
  from t
), t2 as
(
select case
         when weekday = 'SAT' then
          day
       end as day2,
       lvl
  from t
)
select concat( 'Week ', wk1) as week, day1, day2  
  from 
  (
   select row_number() over (order by lvl) wk1, day1
     from t1 where day1 is not null ) t1 
  left join    
  (
   select row_number() over (order by lvl) wk2, day2
     from t2 where day2 is not null ) t2  
    on wk2 = wk1  

by using select .. from dual connect by level syntax and case..when expression to scan all the current year.

Demo

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