DATEDIFF(月)

时间:2017-02-24 11:39:20

标签: sql-server datediff

我有DateDiff(两个日期之间的月数)的问题

当我尝试这个时:

 SELECT
(CASE
WHEN X IS NOT NULL THEN

CONVERT(varchar(4), DATEDIFF(YEAR, Y, C)) + ' years '

ELSE
CONVERT(varchar(4), DATEDIFF(YEAR, A, GETDATE())) + ' years '+
CAST(DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy,GETDATE(),b), S), GETDATE()) AS varchar(4)) +' month '+
CAST(DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy, c, GETDATE()), e), GETDATE()), DATEADD(yy, DATEDIFF(yy, f, GETDATE()), g)), GETDATE()) AS varchar(2)) +' day' end)  as result

FROM g INNER JOIN k ON M=U
WHERE T=XX order by Y;

结果如下所示: 2年342个月2天

但它应该是这样的:2年3个月2天前,

有人可以指出我正确的方向。感谢。

正确答案:

CONVERT(varchar(4), DATEDIFF(dd, x, GETDATE())/365) + ' år '+

CONVERT(varchar(4), DATEDIFF(MONTH, x, GETDATE()) % 12) + ' måneder '+

CAST(DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy, x, GETDATE()), x), GETDATE()), 
DATEADD(yy, DATEDIFF(yy, x, GETDATE()), x)), GETDATE()) AS varchar(2)) +' dag ' end) as Y,

1 个答案:

答案 0 :(得分:0)

您需要进行一些额外的计算。看看这个

declare @AsOnDate datetime
declare @mdob datetime
set @AsOnDate = GETDATE() 
set @mdob = '2014-12-22' 
Select 
"Years" = CASE 
WHEN (DATEPART( DAY , @mdob)) > (DATEPART( DAY , @AsOnDate))
and (DATEPART( Month,@mdob)) = (DATEPART(Month, @AsOnDate))
THEN ((datediff(month,@mdob,@AsOnDate)-1)/12) 
ELSE (datediff(month,@mdob,@AsOnDate)/12) 
END,
"Months" = CASE 
WHEN (DATEPART( DAY , @mdob)) > (DATEPART( DAY , @AsOnDate)) 
and (DATEPART( Month,@mdob)) = (DATEPART( Month,@AsOnDate)) 
THEN ((datediff(month,@mdob,@AsOnDate)-1)% 12) 
ELSE (datediff(month,@mdob,@AsOnDate)% 12) 
END 

从此处采取解决方案: https://www.sqlservercentral.com/Forums/Dialogs/PostDetails.aspx?PostID=1423756