这就是我想象你的“事实表”的样子:
declare @dt datetime
set @dt = '7-1-2012'
;
with date_table as (
select @dt as [Start Date],
dateadd(d,-1,dateadd(mm,1,@dt)) as [End Date],
datepart(d,dateadd(d,-1,dateadd(mm,1,@dt))) as [Days]
union ALL
select dateadd(mm, 1, [Start Date]) as [Start Date],
dateadd(d,-1,dateadd(mm,1,dateadd(mm, 1, [Start Date]))) as [End Date],
datepart(d,dateadd(d,-1,dateadd(mm,1,dateadd(mm, 1, [Start Date])))) as [Days]
from date_table
where dateadd(mm, 1, [Start Date]) <= dateadd(m,500,@dt))
select [Start Date], [End Date], [Days]
into #temp
from date_table
option (MAXRECURSION 0)
这是选择日期。(注意这些语句中没有包含 DATEADD 或 DATEPART)
select finish.[Start Date], finish.[End Date], finish.[Days]
from (select rownum
from (select [Start Date], [End Date], [Days], row_number() over (order by [Start Date]) as rownum
from #temp) as x
where x.[Start Date] = '2012-07-01 00:00:00.000' ) as start
join (select [Start Date], [End Date], [Days],
row_number() over (order by [Start Date]) as rownum
from #temp) as finish
on finish.rownum = start.rownum + 360
我在下面阅读了您的评论...如果您想总结日子或其他事情,这就是您可以做到的:(因此从 2012 年 7 月 1 日开始,持续 360 个月... date_diff_days 结果将是360 个月的总天数...使用我制作的#temp 表...我假设它与您的事实表相似...我有 10957 天)
select sum(dayscount.[Days]) as date_diff_days
from (select rownum
from (select [Start Date], [End Date], [Days], row_number() over (order by [Start Date]) as rownum
from #temp) as x
where x.[Start Date] = '2012-07-01 00:00:00.000' ) as start
join (select [Start Date], [End Date], [Days],
row_number() over (order by [Start Date]) as rownum
from #temp) as finish
on finish.rownum = start.rownum + 360
join (select [Start Date], [End Date], [Days],
row_number() over (order by [Start Date]) as rownum
from #temp) as dayscount
on dayscount.rownum >= start.rownum and
dayscount.rownum < finish.rownum