将Excel中的DateDIF转换为SQL DateDiff

时间:2014-12-08 23:28:48

标签: sql datediff

Excel公式: = DATEDIF(I2,TODAY()" Y")&安培;"年"& DATEDIF(I2,TODAY()," ym")&"几个月"& DATEDIF(I2,TODAY()," md")&"天"

格式如下: 2年9个月6天

想在SQL查询中使用它。

思想?

2 个答案:

答案 0 :(得分:0)

在TSQL中,您可以写为:

-- In case your date column has time also use Datetime for @I2 instead
DECLARE @I2 AS DATE
SET @I2 = '11/9/2014'

-- In TSQL GETDATE() returns current date and time
SELECT CAST (
               DATEDIFF(YY,@I2,GETDATE()) 
               - CASE WHEN (MONTH(@I2) > MONTH(GETDATE())) 
                             OR (MONTH(@I2) = MONTH(GETDATE())
                            AND DAY(@I2) > DAY(GETDATE())) 
                 THEN 1 ELSE 0 END
               AS VARCHAR(4)
            )  +' Years ' +       
       CAST (
               datediff(month, @I2, GETDATE()) 
               - CASE WHEN DAY(@I2) > DAY(GETDATE()) 
                 THEN 1 ELSE 0 END
                AS VARCHAR(4)
             ) +' Months ' +
         CAST(
              DATEDIFF(d, 
                  DATEADD(m, 
                  datediff(month, @I2, GETDATE()) 
                  - CASE WHEN DAY(@I2) > DAY(GETDATE()) 
                  THEN 1 ELSE 0 END
                  , @I2)
                , GETDATE())
               AS VARCHAR(4)
             ) +' Days ' 

答案 1 :(得分:0)

编辑:看来excel实际上确实have a bug

警告:为了支持Lotus 1-2-3中的旧工作簿,Excel提供了DATEDIF函数。在某些情况下,DATEDIF函数可能会计算不正确的结果。有关更多详细信息,请参见本文的已知问题部分。

对于它的价值,我不得不微调一下以使其按预期工作。以下内容在99%的时间内都有效,但据我所知,它可能会在1-3天的任何时间关闭。我进行了1500多个单元测试,在该范围内只有15个失败。

例如,此日期范围12/31 / 1973-12 / 5/2019关闭了一天。要么是excel,要么是有bug!

SELECT CAST (
              DATEDIFF(YY,@I2,GetDate()) 
               - CASE WHEN (MONTH(@I2) > MONTH(GetDate())) 
                             OR (MONTH(@I2) = MONTH(GetDate())
                            AND DAY(@I2) > DAY(GetDate())) 
                 THEN 1 ELSE 0 END
               AS VARCHAR(4)
            )  + ' Years ' +
       CAST (
               datediff(month, @I2, GetDate()) 
               - CASE WHEN DAY(@I2) > DAY(GetDate()) 
                 THEN 1 ELSE 0 END
                 -
                 (DATEDIFF(YY,@I2,GetDate()) 
               - CASE WHEN (MONTH(@I2) > MONTH(GetDate())) 
                             OR (MONTH(@I2) = MONTH(GetDate())
                            AND DAY(@I2) > DAY(GetDate())) 
                 THEN 1 ELSE 0 END) * 12
                AS VARCHAR(4)
             ) + ' Months ' +
         CAST(
              DATEDIFF(d, 
                  DATEADD(m, 
                  datediff(month, @I2, GetDate()) 
                  - CASE WHEN DAY(@I2) > DAY(GetDate()) 
                  THEN 1 ELSE 0 END
                  , @I2)
                , GetDate())
               AS VARCHAR(4)
             ) + ' Days '