sql server中两个日期相减的例子
本文导语: 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、相差年数 select trunc((months_between...
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、相差年数
select trunc((months_between(trunc(sysdate,'dd'),to_date('2009-01-01','yyyy-mm-dd')))/12) from dual;
--4、
select datediff( day, '2008.08.25', '2008.09.01' )
--5、
select datediff( second, '2009-8-25 12:15:12', '2009-9-1 7:18:20') --返回相差秒数
--6、
select datediff( minute, '2009-8-25 12:15:12', '2009-9-1 7:18:20') --返回相差分钟数
--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、
SELECT (CAST(datediff(second,StartDate,EndDate) AS FLOAT)/60)AS D
FROM Inventory WHERE RecordId = 2292549 --获取两个日期之差(单位 M)
实例二
select distinct datediff(day, '2009-3-12', '2009-3-15') as difday
from titles
结果:3
实例三
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