Вот альтернативный подход с использованием стандартных функций SQL Дата:
declare @StartDate datetime = '2016-11-08'
, @EndDate datetime = '2023-10-09' --'2017-02-10'
, @dayOfInterest int = 8 --in case you decided you were interested in a different date
--if you don't care whether or not start date is before or after end date; swap their values...
/*
select @StartDate = min(d)
, @EndDate = max(d)
from (select @StartDate d union select @EndDate) x
*/
select
case when @StartDate <= @EndDate then
--if the end date is after or on the start date, we count the number of eighths in between
datediff(month,@StartDate,@EndDate) --count the number of months between the two dates
+ case when datepart(dd,@StartDate)<[email protected] then 0 else -1 end --if our range excludes the nth this month, exclude it
+ case when datepart(dd,@EndDate)<@dayOfInterest then 0 else 1 end --if our range includes the nth on the last month, include it
else
0 --if the end date is before the start date; we return 0
end
CountTheDays --give the output column a name
Осторожно
NB: Для 8-го это будет работать отлично. Для дат после 28-го числа он не является надежным (вам будет лучше с John Cappelletti's solution), так как моя логика добавит 1 день в месяц, независимо от того, был ли этот месяц в этот день (т. Е. Если подсчитать число 30-х годов между 1-м Январь и 1 марта вы получите 2 вместо 1, так как моя логика предполагает, что 30 февраля будет действительной датой.
NB: Этот метод имеет ограничение, если существует более 2519 ('select count (1) from master ..spt_values ') дней между началом и датой окончания. – JohnLBevan
@JohnLBevan Хорошая точка, исправлено –
Nice :). В этом диапазоне размеров у вас заканчиваются даты SQL, прежде чем вы закончите цифры. 'select dateadd (dd, 6345361, '1753-01-01')' – JohnLBevan