问题
I have below data and want to create sequence number for each ID by adding 29 days to Start Date.
i.e. for ID 1, look for minimum(start date) that will be seq num 1 and then add 29. this will be Seq Num 2 and then go on till we loop through each Auth ID. each time look for max(end date) for each ID. when this loop reaches that value stop it for each value.
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)
Basically, I need to loop through every ID add 29 days for Service date till it reaches max end date and put the seq num. Repeat this for all ID's.
i tried doing CTE to add the 29 days but failing to compare it with end date for an ID.
Can somebody help me?
回答1:
You mean this?
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;
Or this:
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;
来源:https://stackoverflow.com/questions/51885221/loop-through-each-value-to-the-seq-num