2

我需要在两个日期之间得到以下结果:

date_start = 01/01/2010
date_end = 10/21/2012

结果:1年9个月20天。

我尝试了下面的代码,但它不起作用。它有时会返回负日期:

SELECT CAST(DATEDIFF(yy, date_start, date_end) AS varchar(4)) +' year '+
       CAST(DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy,date_start , date_end), date_start), date_end) AS varchar(2)) +' month '+
       CAST(DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy, date_start, date_end), date_start), date_end), DATEADD(yy, DATEDIFF(yy, date_start, date_end), date_start)), date_end) AS varchar(2)) +' day' AS result

谢谢你!

4

3 回答 3

2

如果闰年或与之相邻,这可能无法正确处理闰年,但除此之外,这应该非常接近:@s@e

DECLARE @s DATE, @e DATE

SELECT @s = '20100101', @e = '20121021';

SELECT y + ' year(s), ' + m + ' month(s) and ' + d + ' day(s).'
FROM
(
  SELECT 
    RTRIM(y), 
    RTRIM(m - CASE WHEN pd < 0 THEN 1 ELSE 0 END),
    RTRIM(CASE WHEN pd < 0 THEN nd ELSE pd END)
  FROM 
  (
    SELECT
      DATEDIFF(MONTH, @s, @e) / 12, 
      DATEDIFF(MONTH, @s, @e) % 12,
      DATEDIFF(DAY, @s, DATEADD(MONTH, -DATEDIFF(MONTH, @s, @e), @e)),
      DATEDIFF(DAY, @s, DATEADD(MONTH, 1-DATEDIFF(MONTH, @s, @e), @e))
  ) AS x (y, m, pd, nd)
) AS y (y, m, d);

输出:

2 year(s), 9 month(s) and 20 day(s).

如果在闰年考虑额外的一天是至关重要的,我相信可以调整它来处理这个问题。尽管通过最少的测试,我无法看到它会中断的任何情况(它只是觉得它不应该工作)。

于 2012-09-25T18:26:56.063 回答
0

试试这个

DECLARE @months decimal (5,2)
SELECT @months = DATEDIFF(month, '01/22/2010','10/21/2012')/12.0

;WITH CTE AS 
(
SELECT FLOOR(@months) AS years,(@months-FLOOR(@months)) * 12 AS months
)
SELECT years, CAST(months as int) months, 
case when day('01/22/2010') > day('10/21/2012')  
then day('10/21/2012') +  
datediff(day,'01/22/2010',dateadd(month,datediff(month,0,'01/22/2010')+1,0))- 1
ELSE day('10/21/2012')-day('01/22/2010') end
from cte
于 2012-09-25T18:22:04.237 回答
0

您可以使用函数获取日期差异也可以看到这个 http://atikpassion.blogspot.com/2014/01/get-difference-between-two-dates-in.html

于 2014-01-21T11:05:49.870 回答