I have a table as follows: (Expected result without weekend exclude logic)
Start Date | End Date(Expected Date) | No of Days(input) |
---|---|---|
01-01-2021 | 02-01-2021 | 2 |
03-01-2021 | 08-01-2021 | 5 |
09-01-2021 | 10-01-2021 | 2 |
11-01-2021 | 20-01-2021 | 10 |
21-01-2021 | 09-02-2021 | 20 |
10-02-2021 | 10-02-2021 | 1 |
I want to re-generate the StartDate
and EndDate
data based on the NumberOfDays
values, and the StartDate
for subsequent rows based on previous row's EndDate + 1 day
and in this sequence, I need to exclude the weekend dates as well, and I have another scenario to include weekend dates based on condition.
I want to apply this logic and select the data in same select query using SQL Server.
This is what I have tried
declare @t table ( StartDate date, EndDate date, DaysToAdd int );
insert into @t(StartDate, EndDate, DaysToAdd)
values('20210217', '20210227', 10), ('20210312', '20210310', 10), ('20210326', '20210401', 10), ('20210409', '20210401', 10), ('20210507', '20210401', 10), ('20210606', '20210529', 10), ('20210618', '20210417', 3), ('20210620', '20210309', 2), ('20300913', '20210227', 2), (null, '20300914', 4);
select * from @t
select dateadd(day, -DaysToAdd-1+count(*) over(order by isnull(StartDate, EndDate), EndDate) + sum(DaysToAdd) over(order by isnull(StartDate, EndDate), EndDate), min(StartDate) over()) as NewStartDate, dateadd(day, -1+count(*) over(order by isnull(StartDate, EndDate), EndDate) + sum(DaysToAdd) over(order by isnull(StartDate, EndDate), EndDate), min(StartDate) over()) as NewEndDate, * from @t;
My Expected result:
Start Date | End Date(Expected Date) | No of Days(input) |
---|---|---|
01-01-2021 | 04-01-2021 | 2 |
05-01-2021 | 11-01-2021 | 5 |
12-01-2021 | 13-01-2021 | 2 |
14-01-2021 | 27-01-2021 | 10 |
28-01-2021 | 24-02-2021 | 20 |
25-02-2021 | 25-02-2021 | 1 |