Я создал таблицу календаря для хранения дат и флага «isweekend», затем, исключив даты выходных и упорядочив две таблицы, вы можете объединить их, чтобы получить необходимые данные
use tempdb
GO
-- create a calendar table
drop table if exists #calendar
GO
CREATE TABLE #calendar(
[date] date
, isweekend AS (IiF((datename(weekday,[date])) IN ('Saturday', 'Sunday'), 1, 0))
)
--populate with data from 2000 onwards (100000 days)
; with numbers as (
select ROW_NUMBER() over(order by (select null)) as n from sys.columns o1
cross join sys.columns o2
)
insert into #calendar ([date])
select dateadd(day, numbers.n -1, '20000101') from numbers
where numbers.n < 100000
go
drop table if exists #originaldate
GO
create table #originaldate (
original date
)
GO
insert into #originaldate (original)
values ('20191004'), ('20191005'), ('20191006'), ('20191007'), ('20191008'), ('20191009'), ('20191010'), ('20191011'), ('20191012'), ('20191013')
select * from #originaldate
GO
; with weekdays as ( -- we only want weekdays, in date order
select [date], row_number() over (order by [date] asc) as rn
from #calendar c
where c.isweekend = 0
and date >= '20191004' -- IMPORTANT, you must start row number at the same date as the table you want to match againt
)
, originals as ( -- order the dates we are matching
select original, ROW_NUMBER() over (order by [original] asc) as rn
from #originaldate
)
select o.original, w.date as updateddate
from weekdays w
inner join originals o
on o.rn = w.rn
order by o.original ASC