您的位置:首页 > 数据库

Sql Server 获取表中今天、昨天、本周、上周、本月、上月等数据

2016-07-09 16:11 561 查看
在做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


昨天早上8点到今天早上10点的数据

select * from tb where dates between convert(varchar(10),getdate()-1,120)+' 08:00:00' and convert(varchar(10),getdate(),120)+' 10:00:00'

转载地址:http://www.devdo.net/sql-server-query-date.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: