sql datediff 計算時間差

來源:互聯網
上載者:User

有關datediff的相應資訊,見如下:

 

DATEDIFF (datepart ,startdate ,enddate )
datepart

是指定所跨邊界類型的 startdate 和 enddate 的一部分。下表列出了所有有效 datepart 參數。使用者定義的變數等效項是無效的。

datepart

縮寫

year

yy, yyyy

quarter

qq, q

month

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。

為避免不確定性,請使用四位元年份。有關兩位元年份的資訊,請參閱two digit year cutoff 選項。

enddate

請參閱 startdate。

 

 

1.返回相差兩個季度時間得記錄

代碼如下:需要時,可以將時間欄位改為資料庫中相應的欄位

View Code 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個月的訂單。

代碼如下:

View Code 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.

 

 

 

 

 

 

 

具體可參考:TechNet

              :datediff

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.