-3

enter image description here

In the picture I count the number of days between two dates excluding the extra day of the leap years.

How can this be done in SQL Server 2008 R2?

4

1 回答 1

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);

SQL小提琴

于 2014-06-05T06:43:47.680 回答