日期之间的SQL差异(年,月,日)

时间:2016-12-14 21:40:50

标签: sql sql-server

我在使用函数的年,月,日之间获得两个日期之间存在差异,只有Select语句。

到目前为止,我有这个混乱的代码,但它不能很好地工作,因为有时月/日是 - 。 tblProject.BillingDate是StartDate,tblServiceTicket.ServiceTicketDate是EndDate。

         CONVERT(varchar(12),datediff(YEAR,tblProject.BillingDate,tblServiceTicket.ServiceTicketDate))  + ' year, '
        + CONVERT(varchar(12),DATEDIFF(MM, DATEADD(YY, datediff(YEAR,tblServiceTicket.ServiceTicketDate,tblProject.BillingDate), tblServiceTicket.ServiceTicketDate), tblProject.BillingDate)) + ' months, '
        + CONVERT(varchar(12),DATEDIFF(DD, DATEADD(MM, DATEDIFF(MM, DATEADD(YY, (datediff(YEAR,tblProject.BillingDate,tblServiceTicket.ServiceTicketDate)), tblProject.BillingDate), tblServiceTicket.ServiceTicketDate), DATEADD(YEAR, datediff(YEAR,tblProject.BillingDate,tblServiceTicket.ServiceTicketDate) , tblProject.BillingDate)), tblServiceTicket.ServiceTicketDate)) + ' days '

1 个答案:

答案 0 :(得分:1)

我知道这样做的唯一方法是半迭代,就像这样。这个版本可以通过围绕DATEDIFF进行编码来改进,但它显示的逻辑比DATEDIFF版本更清晰。

DECLARE @dstart datetime, 
    @dend datetime,
    @dwork datetime

DECLARE @yy int, 
    @mm int, 
    @dd int

SET @dstart = '19570125'
SET @dend = '20161214'

DECLARE @ix int

-- Get Year interval
SET @ix = 0
WHILE @ix >= 0
BEGIN
    Set @ix = @ix + 1
    IF Dateadd(year, @ix, @dstart) > @dend
    BEGIN
        SET @yy = @ix - 1
        SET @ix = -1
    END
END

Set @dwork = Dateadd(year, @yy, @dstart)

-- Get month interval
SET @ix = 0
WHILE @ix >= 0
BEGIN
    Set @ix = @ix + 1
    IF Dateadd(MONTH, @ix, @dwork) > @dend
    BEGIN
        SET @mm = @ix - 1
        SET @ix = -1
    END
END

Set @dd = DATEDIFF(day, dateadd(month, @mm, @dwork), @dend)

SELECT 'The difference is ' + Cast(@yy as varchar) + ' years, ' + Cast(@mm as varchar) + ' Months, and ' + Cast(@dd as varchar) + ' Days'

以下是一些示例输出,显示了它如何处理几个问题情况。

-- One day at new years
SET @dstart = '20161231'
SET @dend = '20170101'

-- The difference is 0 years, 0 Months, and 1 Days

-- One month to a shorter month
SET @dstart = '20160131'
SET @dend = '20170228'

-- The difference is 1 years, 1 Months, and 0 Days

-- My age
SET @dstart = '19570125'
SET @dend = '20161214'

-- The difference is 59 years, 10 Months, and 19 Days