【问题标题】:How do you count the number of days between two dates excluding the extra day in leap years [closed]你如何计算两个日期之间的天数,不包括闰年的额外一天[关闭]
【发布时间】:2014-06-05 01:44:59
【问题描述】:

在图片中,我计算了两个日期之间的天数,不包括闰年的额外一天。

如何在 SQL Server 2008 R2 中做到这一点?

【问题讨论】:

  • 我无法回答我自己的问题,我只获得了 9 个声誉
  • @g2_player 但您仍然可以编辑您的问题并添加 cmets。请向我们展示您用于获取结果的查询。
  • 我正在寻找其他解决方案
  • 如果你不展示你所做的,很难判断我提供的解决方案是否是“另一种解决方案”。

标签: sql-server sql-server-2008-r2 leap-year


【解决方案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 Fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    相关资源
    最近更新 更多