我有以下数据,想通过为“开始日期”增加29天来为每个ID创建序号。
即对于ID 1,请查找将等于1的最小值(开始日期) 然后添加29。这将是Seq Num 2,然后继续直到我们遍历每个Auth ID。 每次寻找每个ID的最大值(结束日期)。当此循环达到该值时,请为每个值停止它。
ID StartDate EndDate
1 2017-01-01 2017-01-15
1 2017-01-15 2017-02-14
2 2017-01-01 2017-01-15
2 2017-01-05 2017-03-05
2 2017-01-10 2017-02-04
3 2017-01-01 2017-01-15
3 2017-01-16 2017-01-16
3 2017-01-17 2017-01-21
3 2017-01-22 2017-02-13
3 2017-02-14 2017-03-21
3 2017-02-16 2017-03-21
4 2017-01-01 2017-01-15
4 2017-01-16 2017-02-16
4 2017-01-19 2017-02-16
4 2017-02-17 2017-03-17
4 2017-03-18 2017-03-30
4 2017-03-22 2017-03-30
4 2017-03-31 2017-04-28
Expected OutPut
ID SeqNum StartDate EndDate New Date
1 1 2017-01-01 2017-01-15 2017-01-30
1 2 2017-01-15 2017-02-14 2017-02-28 (2017-02-28 is > than max(end date) for this ID so pick the next ID)
2 1 2017-01-01 2017-01-15 2017-01-30
2 2 2017-01-05 2017-03-05 2017-02-28
2 3 2017-01-10 2017-02-04 2017-03-29 (2017-03-29 is > than max(end date-2017-03-05) for this ID so pick the next ID)
基本上,我需要遍历每个ID,为服务日期添加29天,直到达到最大结束日期,然后输入seq num。 对所有ID重复此操作。
我尝试进行CTE添加29天,但未能将其与ID的结束日期进行比较。
有人可以帮我吗?
答案 0 :(得分:0)
你是这个意思吗?
with myData as
(
select ID,
row_Number() over (partition by Id order by id, StartDate) as SeqNum,
min(startdate) over (partition by Id) as minDate,
startDate, endDate
from myTable
)
select id, seqNum, startDate, endDate, dateadd(day, seqNum*29, minDate) as newDate
from myData;
或者这个:
with myData as
(
select ID,
row_Number() over (partition by Id order by id, StartDate) as SeqNum,
min(startdate) over (partition by Id) as minDate,
max(endDate) over (partition by Id)as maxDate,
startDate, endDate
from myTable
)
select id, seqNum, startDate, endDate,
case
when maxDate < dateadd(day, seqNum*29, minDate)
then maxDate
else dateadd(day, seqNum*29, minDate) end as newDate
from myData;