计算SQL中两个日期之间的完整月数 [英] Calculating number of full months between two dates in SQL
本文介绍了计算SQL中两个日期之间的完整月数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在 SQL 中计算 FULL 月的数量,即
I need to calculate the number of FULL month in SQL, i.e.
- 2009-04-16 到 2009-05-15 => 0 个整月
- 2009-04-16 至 2009-05-16 => 1 个月
- 2009-04-16 至 2009-06-16 => 2 个月
我尝试使用 DATEDIFF,即
I tried to use DATEDIFF, i.e.
SELECT DATEDIFF(MONTH, '2009-04-16', '2009-05-15')
但不是给我两个日期之间的完整月份,而是给我月份部分的差异,即
but instead of giving me full months between the two date, it gives me the difference of the month part, i.e.
1
有人知道如何在 SQL Server 中计算整月数吗?
anyone know how to calculate the number of full months in SQL Server?
推荐答案
原来的帖子有一些bug...所以我重新写了,打包成UDF.
The original post had some bugs... so I re-wrote and packaged it as a UDF.
CREATE FUNCTION FullMonthsSeparation
(
@DateA DATETIME,
@DateB DATETIME
)
RETURNS INT
AS
BEGIN
DECLARE @Result INT
DECLARE @DateX DATETIME
DECLARE @DateY DATETIME
IF(@DateA < @DateB)
BEGIN
SET @DateX = @DateA
SET @DateY = @DateB
END
ELSE
BEGIN
SET @DateX = @DateB
SET @DateY = @DateA
END
SET @Result = (
SELECT
CASE
WHEN DATEPART(DAY, @DateX) > DATEPART(DAY, @DateY)
THEN DATEDIFF(MONTH, @DateX, @DateY) - 1
ELSE DATEDIFF(MONTH, @DateX, @DateY)
END
)
RETURN @Result
END
GO
SELECT dbo.FullMonthsSeparation('2009-04-16', '2009-05-15') as MonthSep -- =0
SELECT dbo.FullMonthsSeparation('2009-04-16', '2009-05-16') as MonthSep -- =1
SELECT dbo.FullMonthsSeparation('2009-04-16', '2009-06-16') as MonthSep -- =2
这篇关于计算SQL中两个日期之间的完整月数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文