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:
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 |
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;
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.