sql日期相减得到天数【sql日期时间相减语句】

sql日期时间相减语句

本款教程利用了datediff函数,来对数据库教程的日期进行相减查询哦,下面便写了n种关于mssql 日期相减的方法。

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")

实例二

use pubs

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语句该怎么写???

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%60)

from

(select date=datediff(mi,1,dateadd(d,endday-beginday,beginday)-begintime+endtime)from @t )t

date

-------------------------

20:20

64:10

方法二

declare @t table(开始天数 varchar(10),开始时间 varchar(10),到达天数 varchar(10),到达时间 varchar(10))

insert @t select "1", "16:00","2","12:20"

--如果开始天数,到达天数大于31

select 到达天数 * 24 + datepart(hh,到达时间) - 开始天数 * 24 - datepart(hh,开始时间)

from @t