sql datediff 计算时间差

有关datediff的相应信息,见以下:数据库

DATEDIFF (datepart ,startdate ,enddate )

datepart函数

是指定所跨边界类型的 startdate 和 enddate 的一部分。下表列出了全部有效的 datepart 参数。用户定义的变量等效项是无效的。字符串

dateparttable

缩写变量

yeardate

yy, yyyyselect

quarter搜索

qq, qim

monthqq

mm, m

dayofyear

dy, y

day

dd, d

week

wk, ww

hour

hh

minute

mi, n

second

ss, s

millisecond

ms

microsecond

mcs

nanosecond

ns

startdate

是一个表达式,能够解析为 time、date、smalldatetime、datetime、datetime2 或 datetimeoffset 值。date 能够是表达式、列表达式、用户定义的变量或字符串文字。从 enddate 减去 startdate。

enddate

请参阅 startdate。

1.返回相差两个季度时间得记录

代码以下:须要时,能够将时间字段改成数据库中相应的字段

1 declare @startDateTime datetime
2 declare @endDateTime datetime
3 set @startDateTime='2011-01-01'
4 set @endDateTime='2011-07-10'
5 select DATEDIFF(QQ,@startDateTime,@endDateTime)

2.搜索最近3个月的订单。

代码以下:

declare @startDateTime datetime
declare @endDateTime datetime
set @startDateTime='2011-05-01'
set @endDateTime=GETDATE()
select DATEDIFF(m,@startDateTime,@endDateTime)

3.返回第一单订单时间到最近的一单订单时间的 天数差。

select DATEDIFF(DAY,(select MIN(insDT) from OP_Order),(select MAX(insDT) from OP_Order))

4.使用GETDATE()函数来得到当前时间,

  若使用GetDate()+1,结果是在如今的时间上多添加一天。

如:

   GetDate():  2011-08-13 13:53:09.243

   GetDate()+1 :  2011-08-14 13:53:09.243

   如上,直接在时间的日上加1.

五、使用以下 SELECT 语句:

SELECT DATEDIFF(day,'2008-12-29','2008-12-30') AS DiffDate

结果:

DiffDate

1  

六、使用以下 SELECT 语句:

SELECT DATEDIFF(day,'2008-12-30','2008-12-29') AS DiffDate

结果:

DiffDate

-1   

相关文章
相关标签/搜索