關於SqlServer中datediff用法

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用法內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: