Skip to content
Advertisement

Calculate Week Numbers based on the initial given date to end date

I have below scenario that Business want to calculate Week Number based on Given Start Date to End Date.

For Ex: Start Date = 8/24/2020 End Date = 12/31/2020 ( These Start date & end date are not constant they may change from year to year )

Expected Output below:

I need Oracle Query to calculate Week Number(s) like above .. Based on Start date for 7 days then week number will be calcuated.. But remember that crossing months some month have 30 days and some month 31 days etc.. How to calculate ? Appreciate your help!!

Advertisement

Answer

Seems your looking for custom week definition rather that built-ins. But not overly difficult. The first thing is to convert from strings to dates (if columns actually coming off table this conversion is not required), and from there let Oracle do all the calculations as you can apply arithmetic operations to dates, except adding 2 dates. Oracle will automatically handle differing number of days per month correctly. Two methods for this request:

  1. Use a recursive CTE (with)
  1. Use Oracle connect by

Depend on how strict you need to be with the end date specified you may need to adjust the last row returned. Both queries do not make adjust for that. They just ensure no week begins after that date. But the last week contains the full 7 days, which may end after the specified end date.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement