如何比较两个date在SQL Server 2005中查找时间差,date操作

我有两列:

job_start job_end 2011-11-02 12:20:37.247 2011-11-02 13:35:14.613 

如何使用T-SQL来查找作业开始和作业结束之间的时间间隔?

我试过这个:

 select (job_end - job_start) from tableA 

但结果是:

 1900-01-01 01:14:37.367 

看看DateDiff()函数。

 -- Syntax -- DATEDIFF ( datepart , startdate , enddate ) -- Example usage SELECT DATEDIFF(DAY, GETDATE(), GETDATE() + 1) AS DayDiff SELECT DATEDIFF(MINUTE, GETDATE(), GETDATE() + 1) AS MinuteDiff SELECT DATEDIFF(SECOND, GETDATE(), GETDATE() + 1) AS SecondDiff SELECT DATEDIFF(WEEK, GETDATE(), GETDATE() + 1) AS WeekDiff SELECT DATEDIFF(HOUR, GETDATE(), GETDATE() + 1) AS HourDiff ... 

你可以看到它在行动/ 玩在这里

您可以使用DATEDIFFfunction获取分钟,秒,天等的差异。

 SELECT DATEDIFF(MINUTE,job_start,job_end) 

MINUTE显然会以分钟为单位返回差异,您还可以使用DAY,HOUR,SECOND,YEAR(请参阅书籍在线链接了解完整列表)。

如果你想得到花式的,你可以用不同的方式显示,例如:75分钟可以像这样显示:01:15:00:0

这里是SQL Server 2005和2008的代码

 -- SQL Server 2005 SELECT CONVERT(VARCHAR(10),DATEADD(MINUTE,DATEDIFF(MINUTE,job_start,job_end),'2011-01-01 00:00:00.000'),114) -- SQL Server 2008 SELECT CAST(DATEADD(MINUTE,DATEDIFF(MINUTE,job_start,job_end),'2011-01-01 00:00:00.000') AS TIME) 

将结果转换为TIME ,结果将以时间间隔持续时间格式。

 select CAST(job_end - job_start) AS TIME(0)) from tableA 

我想你需要job_start和job_end之间的时间差距。

尝试这个…

 select SUBSTRING(CONVERT(VARCHAR(20),(job_end - job_start),120),12,8) from tableA 

我结束了这个。

 01:14:37 

如果您的数据库StartTime = 07:00:00StartTime = 07:00:00 = 14:00:00 ,并且都是时间types。 您的查询来获得时差将是:

 SELECT TIMEDIFF(Time(endtime ), Time(StartTime )) from tbl_name 

如果你的数据库的startDate = 2014-07-20 07:00:00和endtime = 2014-07-20 23:00:00 ,你也可以使用这个查询。

声明开始date和结束dateDECLARE @SDATE AS DATETIME

 TART_DATE AS DATETIME DECLARE @END_-- Set Start and End date SET @START_DATE = GETDATE() SET @END_DATE = DATEADD(SECOND, 3910, GETDATE()) 

– 获取结果HH:MI:SS:MMM(24H)格式SELECT CONVERT(VARCHAR(12), DATEADD(MS, DATEDIFF(MS, @START_DATE, @END_DATE), 0), 114) AS TimeDiff

在Sql Server中试试这个

 SELECT start_date as firstdate,end_date as seconddate ,cast(datediff(MI,start_date,end_date)as decimal(10,3)) as minutediff ,cast(cast(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60) as int ) as varchar(10)) + ' ' + 'Days' + ' ' + cast(cast((cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60) - floor(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60)) ) * 24 as int) as varchar(10)) + ':' + cast( cast(((cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60) - floor(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60)))*24 - cast(floor((cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60) - floor(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60)))*24) as decimal)) * 60 as int) as varchar(10)) FROM [AdventureWorks2012].dbo.learndate 

看看DATEDIFF ,这应该是你在找什么。 它需要你比较的两个date,你需要的date单位(天,月,秒…)