[英]Custom Week Number SQL
I need to convert the following logic to python and SQL (SQL query is more imp):我需要将以下逻辑转换为 python 和 SQL (SQL 查询更 imp):
I have a table with ID and Date columns.我有一个包含 ID 和日期列的表。 I need to add a column called "Week_Num" such that:
我需要添加一个名为“Week_Num”的列,以便:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.