如何获得两个日期之间的差异,以获得像结果为2天,23小时,56分钟的结果

时间:2016-07-19 14:27:08

标签: sql sql-server sql-server-2012

如何在sql server 2012中获取两个日期之间的差异。我正在使用此select语句。我希望结果为

select (getdate()-2) - (GetDATE()) as 'Diff'

Result as 2 Days, 23 hours, 56 mins

1 个答案:

答案 0 :(得分:2)

DECLARE @DAT1 datetime = '20160401 13:10:23';
DECLARE @DAT2 datetime = '20160405 12:15:22';


select FLOOR(ABS(datediff(SECOND, @dat1,@dat2)) / 24 / 3600) as 'DAYS', 
       FLOOR(ABS(datediff(SECOND, @dat1,@dat2)) / 3600) % 24 'HOURS',
       FLOOR(ABS(datediff(SECOND, @dat1,@dat2)) / 60) % 60 'MINUTES',
       ABS(datediff(SECOND, @dat1,@dat2))  % 60 'SECONDS'

在那种情况下

    select CAST(FLOOR(ABS(datediff(SECOND, @dat1,@dat2)) / 24 / 3600) as nvarchar(10)) + 
        ' DAYS, ' + 
        CAST(FLOOR(ABS(datediff(SECOND, @dat1,@dat2)) / 3600) % 24 as nvarchar(2)) +  
        ' HOURS, ' + 
        CAST((ABS(datediff(SECOND, @dat1,@dat2)) / 60) % 60  as nvarchar(2)) + 
        ' MINUTES';