我想计算2月25/02/2019
起的天数,预期结果是4
我尝试在SQL Server中使用master..spt_values
,但没有得到预期的结果
declare @fdays int ,@d date=cast('20190201' as date),@JoinDate date=cast('20190225' as date)
select count(dateadd(dd,number,@d)) from master..spt_values
where type = 'p'
and month(dateadd(dd,number,@d))=month(@d)
and year(dateadd(dd,number,@d))=year(@d)
and cast(GETDate() as date)>= Cast(dateadd(dd,number,@JoinDate) as date )
以上代码的结果是28,但我想要4
请帮助我找到预期的结果
答案 0 :(得分:3)
这是简单的日期算术,您无需使用spt_values
:
declare @d date = '20190225';
select datediff(month,0,@d) as MonthsDiff -- Months since an arbitrary date
,dateadd(month,datediff(month,0,@d)+1,0) as StartOfFollowingMonth -- Add months above +1 to same arbitrary date
,datediff(day,@d,dateadd(month,datediff(month,0,@d)+1,0)) as DaysBetweenGivenDate -- DATEDIFF between given date and start of month from above;
输出:
+------------+-------------------------+----------------------+
| MonthsDiff | StartOfFollowingMonth | DaysBetweenGivenDate |
+------------+-------------------------+----------------------+
| 1429 | 2019-03-01 00:00:00.000 | 4 |
+------------+-------------------------+----------------------+
答案 1 :(得分:0)
尝试一下:
declare @date date='20140603'
select datediff(day, @date, dateadd(month, 1, @date))-day(@date)
答案 2 :(得分:0)
从SQL Server 2012开始,您可以仅使用EOMONTH函数:
SELECT DATEDIFF(DAY, '20190225', EOMONTH ('20190225')) + 1 [thedays]
= 4。