SQL Server:如何格式化时间间隔?

时间:2012-02-13 07:41:29

标签: sql sql-server-2005

我想格式化时间间隔,如'99d 99h 99m'。请参阅以下SQL示例:

-- 1501 minutes should be '1d 1h 1m' (= 1 day + 1 hour + 1 minute)
select datediff(mi, '02-21-2012 00:00', '02-22-2012 01:01') 

我的RDBMS是SQL Server 2005.有什么聪明的方法可以做到吗?

3 个答案:

答案 0 :(得分:2)

select CAST(datediff(dd, '02-21-2012 00:00', '02-22-2012 01:01') AS VARCHAR(12))+'d '+
CAST(datediff(hh, '02-21-2012 00:00', '02-22-2012 01:01')%24 AS VARCHAR(2))+'h '+
CAST(datediff(n, '02-21-2012 00:00', '02-22-2012 01:01')%60 AS VARCHAR(2))+'m'

如果您想拥有前导零,除了RIGHT之外,您还必须使用CAST。我把它留下来让查询更容易阅读。

答案 1 :(得分:2)

SELECT [day] = Datediff(dd, st, et),
       [hour] = Datediff(hh, st, et) % 24,
       [minute] = Datediff(n, st, et) % 60
FROM   (SELECT st = CONVERT(DATETIME, '02-21-2012 00:00'),
               et = CONVERT(DATETIME, '02-22-2012 01:01')) tbl  

我不想多次输入'02 -21-2012 00:00'..

答案 2 :(得分:0)

首先得到时间间隔之间的分钟,你必须找到99d 99h 99m格式的间隔。我只是硬编码,所以你的查询将是:

declare @minutes int = 5690

select cast(@minutes/(24*60) as varchar(10))+'d '+cast((@minutes%(24*60))/60 as varchar(10))+'h '+cast((@minutes%(24*60))%60 as varchar(10))+'m'