sql日期相减实例代码
本文导语: 本节内容: sql数据库中两个日期相减 1、相差天数 代码示例: select trunc(sysdate,'yyyy')-to_date('2009-01-04','yyyy-mm-dd') from dual; 代码示例: 2、相差月数 select months_between(trunc(sysdate,'mm'),to_date('2009-01','yyyy-mm')) from dual; 3、相差年...
本节内容:
sql数据库中两个日期相减
1、相差天数
select months_between(trunc(sysdate,'mm'),to_date('2009-01','yyyy-mm')) from dual;
3、相差年数
4、
5、
6、
7、
问题三:select datediff( day, 2009-8-25 12:15:12', 2009-9-1 7:18:20')
8、
FROM Inventory WHERE RecordId = 2292549 --获取两个日期之差(单位 M)
实例二
select distinct datediff(day, '2009-3-12', '2009-3-15') as difday
from titles
结果:3
实例三
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
例如上条记录得到的就是(2*24:00+12:20)-(24:00+16:00)=20:00
这样的sql语句该怎么写?
(
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
方法二
insert @t select '1', '16:00','2','12:20'
--如果开始天数,到达天数大于31
select 到达天数 * 24 + datepart(hh,到达时间) - 开始天数 * 24 - datepart(hh,开始时间)
from @t