简体   繁体   English

自定义周数 SQL

[英]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”的列,以便:

  1. Every time it sees a new ID, Week_Num becomes 1每次看到一个新的 ID,Week_Num 就变成 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. 7 个日期对应 1 周,因此如果第一周从 2019 年 10 月 29 日开始,那么第二周将从 2019 年 11 月 5 日开始。这将持续到 ID 不变。 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=24 的第 1 周将从 2019 年 10 月 29 日至 2019 年 11 月 4 日,而 ID=25 的第 1 周将从 2020 年 10 月 25 日至 2020 年 10 月 31 日。
ID ID Date日期 Week_Num周数
24 24 2019-10-29 2019-10-29 1 1
24 24 2019-10-30 2019-10-30 1 1
24 24 2019-10-31 2019-10-31 1 1
24 24 2019-11-01 2019-11-01 1 1
24 24 2019-11-02 2019-11-02 1 1
24 24 2019-11-03 2019-11-03 1 1
24 24 2019-11-04 2019-11-04 1 1
24 24 2019-11-05 2019-11-05 2 2
24 24 .......... ………… . .
24 24 2020-03-14 2020-03-14 . .
25 25 2020-10-25 2020-10-25 1 1
25 25 2020-10-26 2020-10-26 1 1
25 25 2020-10-27 2020-10-27 1 1
25 25 2020-10-28 2020-10-28 1 1
25 25 2020-10-29 2020-10-29 1 1
25 25 2020-10-30 2020-10-30 1 1
25 25 2020-10-31 2020-10-31 1 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM