我在寻找月份的确切日期差异时遇到了一个问题。
我的要求就像
difference in months between two dates in 2015-01-25 00:00:00.000 and 2015-04-25 00:00:00.000 should be 3
difference in months between two dates 2015-01-25 00:00:00.000 and 2015-04-26 00:00:00.000 should be > 3
SELECT DATEDIFF(MONTH, '2015-01-25 00:00:00.000', '2015-04-28 00:00:00.000')
如果使用DATEDIFF函数,则以上两个示例将返回相同的值3。即SELECT DATEDIFF(MONTH,'2015-01-25 25:00:00:00.000','2015-04- 26 00:00:00.000')是3。但是我需要大于3的结果。
我如何使用单个选择查询实现以上要求。
您需要计算月份,然后需要将开始日期提前月份数并计算天数,如下所示:
MS SQL Server 2008架构设置:
查询1:
declare @f datetime, @t datetime
select @f='2015-01-25 00:00:00.000', @t='2015-04-28 00:00:00.000'
SELECT DATEDIFF(MONTH, @f, @t) as m,
datediff(d, dateadd(month, DATEDIFF(MONTH, @f, @t), @f), @t) as d,
DATEDIFF(MONTH, @f, @t) + convert(float, datediff(d, dateadd(month, DATEDIFF(MONTH, @f, @t), @f), @t)) / 30.0 as md
结果:
| M | D | MD |
|---|---|-----|
| 3 | 3 | 3.1 |
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句