0

Hello Iv got big trouble with one query whith next DateTo is counted from previous record.

I have one table

create table #t1 (
M_ID int, --ID of group
STEP int, -- Step number
DateTo Datetime, --DateTo
AddDays int) --Number of days to add to NEXT record

--TestData

INSERT INTO #t1
select 1, 1, GETDATE(), 0 union
select 1, 2, null, 1 union
select 1, 3, null, 0 union
select 1, 4, null, 0 union
select 2, 1, GETDATE(), 0 union
select 2, 2, NULL, 1 union
select 2, 3, NULL, 0 

How table looks.

enter image description here Logic:

If step = 1 then DateTo = GETDATE()
At step 2 of M_ID 1 previous row had 0 days to add so it should copy DateTo from previous row
At step 3 of M_ID 1 previous row has 1 day to add to previous DateTo

Im on the end of my rope...

FAQ Have to be done in T-SQL (8KK records+)

1
  • Please format your question properly. Commented Dec 3, 2013 at 8:33

1 Answer 1

2
;with cte as (
    select M_ID, STEP, DateTo, AddDays
    from #t1
    where STEP = 1
    union all
    select t.M_ID, t.STEP, dateadd(dd, c.AddDays, c.DateTo), t.AddDays
    from #t1 t
    inner join cte c on t.M_ID = c.M_ID and t.STEP = c.STEP + 1
)

select *
from cte
Sign up to request clarification or add additional context in comments.

1 Comment

Works great thank you, was trying with common table expressions before but without succes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.