で私の文を分割する10月1日2及び第八に来ました質問は少し不明ですが、私はあなたがしようとしていることを知っていると信じています。日付の範囲(Month/Dayのみを考慮して)が日付の範囲(@StartDate
と@EndDate
で設定された日付)にわたって発生する回数を調べようとしています。私はあなたがすでにそれを行う方法を知っているので、質問のselect count(*) from TableName
部分が気晴らしであると思います。以下は、分母を得る方法についての答えです。これは、あなたが行う方法を理解しようとしているものです。 2014年12月31日と2014年1月1日 - - 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
どちらの例2015年9月1日は、それぞれ2及び3の所望の結果を思い付きます。これを達成する他の方法があるかもしれませんが、私はRecursive CTEが最善の選択肢であると考えました。
ここであなたが何を求めているのかは分かりにくいです。 2つの日付間の日数、または2つの日付間の月数を調べようとしていますか?もしそうなら、関数DATEDIFF()が必要になるでしょう。何か他のものが必要なら、出力がどのように見えるかの例を挙げてください。 –
私は、4月7日と10月8日が、選択された期間を除いて何回繰り返されているかを尋ねています。 – Justin