需要计算加入日期与今天的年,月,日格式之间的天数差异

时间:2017-02-27 01:00:08

标签: sql sql-server-2008

我有一个名为Dates的表

Opendate        Closedate       
2016-02-26      NULL    
2017-01-01      NULL    
2015-11-11      NULL    

我希望输出为

Opendate    Workingperiod       
2016-02-26  1 years 0 months 1 days         
2017-01-01  0 years 1 months 26 days     
2015-11-27  1 years 3 months 0 days     

我们需要计算opendate和今天的日期以及年月和日格式之间的差异。

是否有任何输入可以共享。

2 个答案:

答案 0 :(得分:1)

我认为这应该有效 - 一些组合日期算术(我正在添加CURRENT_DATE以显示我们正在计算的内容); WITH子句只是你展示的输入。

WITH
input(Opendate,Closedate) AS (
          SELECT DATE '2016-02-26',NULL
UNION ALL SELECT DATE '2017-01-01',NULL
UNION ALL SELECT DATE '2015-11-11',NULL
)
SELECT 
  GETDATE( ) AS current_date
, Opendate
, CAST(DATEDIFF(MONTH, Opendate,GETDATE( )) / 12 AS VARCHAR(3)) + ' years '
+ CAST(DATEDIFF(MONTH, Opendate,GETDATE( )) % 12 AS VARCHAR(3)) + ' months '
+ CAST(
    DATEDIFF(
      DAY
    , Opendate
    , DATEADD(
        MONTH
      , DATEDIFF(MONTH, Opendate,GETDATE( )) * -1
      , GETDATE( )
      )
    ) 
  AS VARCHAR(3)
  ) + ' days'
AS WorkingPeriod
FROM input;

current_date|Opendate  |WorkingPeriod
2017-02-26  |2016-02-26|1 years 0 months 0 days
2017-02-26  |2017-01-01|0 years 1 months 25 days
2017-02-26  |2015-11-11|1 years 3 months 15 days

答案 1 :(得分:1)

CREATE TABLE Dates(Opendate DATE, CloseDate DATE)

INSERT INTO Dates(Opendate, CloseDate) values('2016-02-26', null),('2017-01-01',null),('2015-11-11',null)

SELECT Opendate,
       CASE WHEN DAY(Opendate)>DAY(GETDATE()) THEN 
         CAST(DATEDIFF(month,Opendate,GETDATE())/12 AS VARCHAR(5))+' year '+
         CAST((DATEDIFF(month,Opendate,GETDATE())%12-1) AS VARCHAR(5)) +' month '+
         CAST(DATEDIFF(day,DATEADD(month,DATEDIFF(month,Opendate,GETDATE())-1,Opendate),EOMONTH(DATEADD(month,-1,GETDATE())))+DAY(GETDATE()) AS VARCHAR(5))+' days ' 
         ELSE
           CAST(DATEDIFF(month,Opendate,GETDATE())/12 AS VARCHAR(5))+' year '+
           CAST(DATEDIFF(month,Opendate,GETDATE())%12 AS VARCHAR(5)) +' month '+
           CAST(DATEDIFF(day,DATEADD(month,DATEDIFF(month,Opendate,GETDATE()),Opendate),GETDATE()) AS VARCHAR(5))+' days '
       END AS 'Workingperiod'     
  FROM Dates

在我的剧本之上,希望你觉得它很有用。