首頁 > 軟體

關於SqlServer中datediff用法

2022-11-03 14:01:52

datediff是SQL SERVER裡面的用法,ORACLE沒有

一、作用:返回兩個日期之間的時間間隔

二、語法:datediff(datepart,startdate,enddate)

是後面日期減去前面的日期(enddate-startdate)

1、datepart,規定應在日期的哪一部分計算差額

日期 縮寫

year yy/yyyy

quarter qq/q

Month mm/m

day dd/d

Hour hh/h

minute mi,n

second ss,s

三、測試

SQL SERVER不用像ORACLE一樣寫 select ... from dual,只需要寫select ....就可以了

1、引數是 yyyy的話,統計相差的年份,擷取前4位元進行統計

select datediff(yyyy,'20210928','20200121')test
--select datediff(year,'20210928','20200121')test
--select datediff(yy,'20210928','20200121')test

2、引數是 qq時,統計相差的季度

select datediff(qq,'20210928','20200121')test
--select datediff(q,'20210928','20200121')test
--select datediff(quarter,'20210928','20200121')test

3、引數是 mm的時候,統計相差的月份,擷取前6位進行統計

select datediff(mm,'20210928','20200121')test
--select datediff(m,'20210928','20200121')test
--select datediff(month,'20210928','20200121')test

4、引數是 dd的時候,統計相差的天數

select datediff(dd,'20210928','20200121')test
--select datediff(day,'20210928','20200121')test
--select datediff(d,'20210928','20200121')test

5、引數是 hh的時候,統計相差的小時

select datediff(hour,'20211112 10:00:00','20211112 00:00:00')test_hour
       ,datediff(hh,'20211112 10:00:00','20211112 00:00:00')test_hh

6、引數是 mi的時候,統計相差的分鐘數

select datediff(minute,'20211112 10:00:00','20211112 00:00:00')test_minute
       ,datediff(mi,'20211112 10:00:00','20211112 00:00:00')test_mi
       ,datediff(n,'20211112 10:00:00','20211112 00:00:00')test_n

7、引數是 ss的時候,統計相差的秒數

select datediff(second,'20211112 10:00:00','20211112 00:00:00')test_second
       ,datediff(ss,'20211112 10:00:00','20211112 00:00:00')test_ss
       ,datediff(s,'20211112 10:00:00','20211112 00:00:00')test_s

到此這篇關於關於datediff用法的文章就介紹到這了,更多相關datediff用法內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com