本节内容:
sql中两个日期相减
第一部分:sql 日期相减的实例代码
1、相差天数
2、相差月数
3、相差年数
4、
5、
6、
7、
select datediff( hour, '2009-8-25 12:15:12', 2009-9-1 7:18:20') --返回相差小时数
select datediff( day, 2009-8-25 12:15:12', 2009-9-1 7:18:20')
8、
实例二,sql中日期相减。
结果:3
实例三,sql中日期相减。
select t1.*,t2.RESPONSE_TIME from dbo.CO_ALARM_RECORD t1,dbo.CO_WORK_THRESHOLD t2 where t2.alarm_type_id=t1.alarm_type and datediff( minute, alarm_time, complete_time)>5
declare @dt1 as datetime, @dt2 as datetime;
select @dt1 = '2008-8-4 9:36:41', @dt2 = '2008-8-2 9:33:39';
declare @days as int, @hours as int, @minutes as int, @seconds as int;
set @seconds = datediff( second, @dt2, @dt1);
set @days = @seconds / (24 * 60 * 60)
set @seconds = @seconds - @days * 24 * 60 * 60
set @hours = @seconds / (60 * 60);
set @seconds = @seconds - @hours * 60 * 60
set @minutes = @seconds / 60;
set @seconds = @seconds - @minutes * 60;
select convert(varchar(10), @days ) + '天' + convert(varchar(10), @hours ) + '小时' + convert(varchar(10), @minutes ) + '分' + convert(varchar(10), @seconds ) + '秒';
有一个表,其中有四个字段:开始天数,开始时间,到达天数,到达时间(这四个字段都是varchar类型)
例如:某一条记录: 1 16:00 2 12:20
用 select(到达天数+到达时间)-(开始天数+开始时间) as 花费时间 from table
例如,上条记录得得到:
declare @t table
(
beginday int,
begintime varchar(20),
endday int,
endtime varchar(20)
)
insert @t select 1,'16:00',2,'12:20'
union all select 1,'3:00',3,'19:10'
select
date=rtrim(date/60)+':'+rtrim(date`)
from
(select date=datediff(mi,1,dateadd(d,endday-beginday,beginday)-begintime+endtime)from @t )t
date
-------------------------
20:20
64:10
方法二