Skip to content
Advertisement

Custom Week Number SQL

I need to convert the following logic to python and SQL (SQL query is more imp):

I have a table with ID and Date columns. I need to add a column called “Week_Num” such that:

  1. Every time it sees a new ID, Week_Num becomes 1
  2. 7 dates correspond to 1 week so if the first week begins on 29th Oct 2019 then 2nd week will begin on 5th Nov 2019. This will continue till the ID does not change. For example, in the below table week 1 for ID=24 will be from 29th Oct 2019-4th Nov 2019 while week 1 for ID=25 will be from 25th Oct 2020 – 31st Oct 2020.
ID Date Week_Num
24 2019-10-29 1
24 2019-10-30 1
24 2019-10-31 1
24 2019-11-01 1
24 2019-11-02 1
24 2019-11-03 1
24 2019-11-04 1
24 2019-11-05 2
24 ………. .
24 2020-03-14 .
25 2020-10-25 1
25 2020-10-26 1
25 2020-10-27 1
25 2020-10-28 1
25 2020-10-29 1
25 2020-10-30 1
25 2020-10-31 1

Advertisement

Answer

How about just using date diff of the minimum value:

select t.*,
       floor(datediff(day,
                      min(date) over (partition by id order by date)
                      date
                     ) / 7.0
             ) + 1 as week_num
from t;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement