I have a table filled with dates and I want to group them in 7 day lasting blocks. I also want to mind the gaps between the blocks and treat any date, that comes after preceding block end, as a start of a 7 day period.
Below is my desired output example
Date Block
---------------------
2023-03-02 1
2023-03-03 1
2023-03-04 1
2023-03-10 2
2023-03-16 2
2023-04-04 3
2023-05-02 4
2023-05-05 4
I have an algorithm using the while statement. But its not usable in batch situations as it runs way too slow. Is there some other way?
create table #dates_to_assign (
[Date] date
)
insert into #dates_to_assign values
('2023-03-02'), ('2023-03-03'), ('2023-03-04'), ('2023-03-10'),
('2023-03-16'), ('2023-04-04'), ('2023-05-02'), ('2023-05-05')
create table #dates_assigned (
[Date] date,
[Block] int
)
declare @curr_date date = (select min([Date]) from #dates_to_assign)
declare @block int = 1
WHILE EXISTS(SELECT TOP 1 * from #dates_to_assign)
BEGIN
insert into #dates_assigned
select [Date], [Block] = @block
from #dates_to_assign
where DATEDIFF(DAY, @curr_date, [Date]) < 7
delete from #dates_to_assign
where DATEDIFF(DAY, @curr_date, [Date]) < 7
set @curr_date = (select min([Date]) from #dates_to_assign)
set @block = @block + 1
END
select *
from #dates_assigned
1条答案
按热度按时间e0bqpujr1#
I suspect you need to use recursive cte for this:
This "loops" each date by counter and reset the start date each time you leave the 7 day period. For performance you'd do well to materialize the counter with index, but not sure if it's possible.