用递归构造所有日期,用开窗函数取模分组
with cte as (select Convert(DateTime,'20211201',112) d
union all
select d+1 from cte where d+1<=Convert(DateTime,'20211231',112))
select g ,min(d) date_from,max(d) date_to,sum(val) sum_val from (
select round(((row_number() over (order by cte.d))-1)/5,0,1) g,
cte.d,isnull(val,0) val from cte left join
(select d ,sum(val) val from test_table group by d) a
on cte.d=a.d) as t
group by g;
下面是实测截图