在图片中,我计算两个日期之间的天数,不包括闰年的额外日期。
如何在SQL Server 2008 R2中完成此操作?
答案 0 :(得分:1)
您可以自己构建一个日历表,为每个日期存储一行,以及您需要的有关该日期的额外信息。为了支持您的查询,它可能看起来像。
create table Calendar
(
TheDate date primary key,
LeapDay bit not null
)
您的查询将是。
select count(*)
from Calendar
where TheDate >= @StartDate and
TheDate < @EndDate and
LeapDay = 0
使用某些数据填充日历表的一种方法:
with Numbers(Number) as
(
select top(11000) row_number() over(order by 1/0)
from sys.all_objects as o1, sys.all_objects as o2
), Dates(TheDate) as
(
select dateadd(day, Number-1, cast('2000-01-01' as date))
from Numbers
)
insert into Calendar(TheDate, LeapDay)
select TheDate,
case when datepart(month, TheDate) = 2 and
datepart(day, TheDate) = 29
then 1
else 0
end
from Dates
如果您不想创建支持查询的永久表,可以在CTE中构建一个。
with Dates(TheDate) as
(
select top(datediff(day, @StartDate, @EndDate))
dateadd(day, row_number() over(order by 1/0)-1, @StartDate)
from sys.all_objects as o1, sys.all_objects as o2
)
select count(*)
from Dates as D
where not (datepart(month, D.TheDate) = 2 and datepart(day, D.TheDate) = 29);