sqlserver查詢今天、昨天、本週、上週、本月、上月等資料
阿新 • • 發佈:2018-12-03
在做Sql Server開發的時候有時需要獲取表中今天、昨天、本週、上週、本月、上月等資料,這時候就需要使用DATEDIFF()函式及GetDate()函數了。
DATEDIFF ( datepart , startdate , enddate )
釋義:計算時間差
datepare值:year | quarter | month | week | day | hour | minute | second | millisecond
startdate:開始日期
enddate :結束日期
GetDate()
釋義:獲取當前的系統日期
下面例子中表名為tablename,條件欄位名為inputdate
查詢今天
SELECT * FROM tablename where DATEDIFF(day,inputdate,GETDATE())=0
查詢昨天
SELECT * FROM tablename where DATEDIFF(day,inputdate,GETDATE())=1
查詢本週
SELECT * FROM tablename where datediff(week,inputdate,getdate())=0
查詢上週
SELECT * FROM tablename where datediff(week,inputdate,getdate())=1
查詢本月
SELECT * FROM tablename where DATEDIFF (month,inputdate,GETDATE())=0
查詢上月
SELECT * FROM tablename where DATEDIFF(month,inputdate,GETDATE())=1