SQL Server 我怎样才能得到两个日期在月份上的真实的差别呢?

wnavrhmk  于 2023-02-03  发布在  其他
关注(0)|答案(1)|浏览(104)

我的问题是,当我将日期范围设置为

DECLARE @startdate DATETIME2 = '2023-01-31 08:00:00.0000000';  
DECLARE @enddate   DATETIME2 = '2023-02-01 08:00:00.0000000';   
SELECT DATEDIFF(month, @startdate, @enddate)

结果是一。

ff29svar

ff29svar1#

也许这比您所寻找的更多,但这里有一个表值函数。如果您的数据在表中,则可以单独调用或在CROSS APPLY中调用。

    • 示例**
DECLARE @startdate DATETIME2 = '2023-01-31 08:00:00.0000000';  
DECLARE @enddate   DATETIME2 = dateadd(month,6,getdate()) --'2023-02-01 08:00:00.0000000';   

Select * 
From [dbo].[tvf-Date-Elapsed](@startdate,@enddate)
    • 结果**
Years   Months  Days    Hours   Minutes Seconds
0       5       24      3       2       49
    • 功能(如果感兴趣)**
CREATE FUNCTION [dbo].[tvf-Date-Elapsed] (@D1 DateTime,@D2 DateTime)
Returns Table
Return (
    with cteBN(N)   as (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
         cteRN(R)   as (Select Row_Number() Over (Order By (Select NULL))-1 From cteBN a,cteBN b,cteBN c),
         cteYY(N,D) as (Select Max(R),Max(DateAdd(YY,R,@D1))From cteRN R Where DateAdd(YY,R,@D1)<=@D2),
         cteMM(N,D) as (Select Max(R),Max(DateAdd(MM,R,D))  From (Select Top 12 R From cteRN Order By 1) R, cteYY P Where DateAdd(MM,R,D)<=@D2),
         cteDD(N,D) as (Select Max(R),Max(DateAdd(DD,R,D))  From (Select Top 31 R From cteRN Order By 1) R, cteMM P Where DateAdd(DD,R,D)<=@D2),
         cteHH(N,D) as (Select Max(R),Max(DateAdd(HH,R,D))  From (Select Top 24 R From cteRN Order By 1) R, cteDD P Where DateAdd(HH,R,D)<=@D2),
         cteMI(N,D) as (Select Max(R),Max(DateAdd(MI,R,D))  From (Select Top 60 R From cteRN Order By 1) R, cteHH P Where DateAdd(MI,R,D)<=@D2),
         cteSS(N,D) as (Select Max(R),Max(DateAdd(SS,R,D))  From (Select Top 60 R From cteRN Order By 1) R, cteMI P Where DateAdd(SS,R,D)<=@D2)

    Select [Years]   = cteYY.N
          ,[Months]  = cteMM.N
          ,[Days]    = cteDD.N
          ,[Hours]   = cteHH.N
          ,[Minutes] = cteMI.N
          ,[Seconds] = cteSS.N
          --,[Elapsed] = Format(cteYY.N,'0000')+':'+Format(cteMM.N,'00')+':'+Format(cteDD.N,'00')+' '+Format(cteHH.N,'00')+':'+Format(cteMI.N,'00')+':'+Format(cteSS.N,'00')
     From  cteYY,cteMM,cteDD,cteHH,cteMI,cteSS
)
--Max 1000 years
--Select * from [dbo].[tvf-Date-Elapsed] ('1991-09-12 21:00:00.000',GetDate())

相关问题