2017-11-03 59 views
-2

我正在处理一个存储过程,其中按指定日期范围内重复的月份和日期的间隔划分行数。如何找出存储过程参数中传递的@StartDate和@EndDate之间的日期/月间隔

间隔月份和日期= 4月7日和10月8日

日期范围2014年1月1日和2014年12月31日,4月7日和10月8日被重复2次,所以我会分裂我的发言2.

日期范围2014年1月1日和2015年9月1日,4月7日来到2和第8 10月1日,所以我会用3

+0

有点难以告诉你在这里问什么。你只是试图找出两个日期之间的天数,或两个日期之间的月数?如果是这样,你可能需要函数DATEDIFF()。如果你想要别的东西,你能举个例子说明你期望输出的样子吗? –

+0

我所要求的是4月7日和10月8日在不包括年份的选定期间内重复多少次。 – Justin

回答

2

正如其他人说分我的发言,这个问题有点不清楚,但我相信我知道你在做什么。您正在尝试查找一组日期(仅考虑月/日计算)发生的日期范围(由@StartDate@EndDate设置)的次数。我认为select count(*) from TableName问题的一部分是一个分心,因为你已经知道如何做到这一点。以下是如何得到分母的答案,这正是你想要弄清楚如何去做的。 2014年12月31日和2014年1月1日 - -

declare @StartDate date = '2014-01-01' 
    , @EndDate date = '2014-12-31' 
    , @DenVal int --Denominator Value 

create table #dates_of_interest 
    (
     month_nbr tinyint not null 
     , day_nbr tinyint not null 
    ) 

insert into #dates_of_interest 
values (4, 7) --7th of April 
    , (10, 8) --8th of October 

; with date_list as 
    (
     --use a Recursive CTE to generate a list of all the dates in the given range. 
     select @StartDate as dt 
     union all 
     select dateadd(d,1,dt) as dt 
     from date_list 
     where 1=1 
     and dt < @EndDate 
    ) 
--Get the output of the Recursive CTE along with Month/Day numbes 
select dt 
, datepart(m,dt) as month_nbr 
, datepart(d,dt) as day_nbr 
into #list_of_dates 
from date_list as dl 
option (maxrecursion 32767) --set to max possible levels of recursion (might want to lower this number) 

--Set the Denominator to the results of the sum(case/when) AKA countif 
set @DenVal = 
    (
     select sum(case when di.month_nbr is null and di.day_nbr is null then 0 else 1 end) 
     from #list_of_dates as ld 
     left join #dates_of_interest as di on ld.month_nbr = di.month_nbr 
              and ld.day_nbr = di.day_nbr 
    ) 

Print @DenVal 

的2014年1月1日两个例子都2015年9月1日提出了分别的2和3的期望的结果。可能还有其他方法来完成这个,但我认为Recursive CTE是最好的选择。

+0

谢谢,这就是我一直在寻找的东西。 – Justin

相关问题