答案 0 :(得分:2)
您可以使用递归CTE来实现,
例如:(我假设您的日期列为MM / DD / YYYY格式)
;with orig_src as
(
select CAST('01/01/2018' AS DATETIME) As Dt, 'Alpha' Name, 3 Freq
UNION ALL
select CAST('12/01/2018' AS DATETIME) As Dt, 'Beta' Name, 2 Freq
), freq_cte as
(
--start/anchor row
select dt, name, 1 freq_new, Freq rn from orig_src
--recursion
union all
select DATEADD(MONTH, 1, a.dt), a.name, 1 freq_new, a.rn - 1 from freq_cte a
--terminator/constraint for recursion
where a.rn - 1 ! = 0
)
select convert(varchar, dt, 101) dt, name, freq_new from freq_cte
order by 2,1
这种递归逻辑的工作方式是 首先,我们从表中的CTE(freq_cte)中获取所有行,然后递归调用此CTE,并递减rn(原始freq),直到满足(rn -1)= 0的终止条件为止。