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
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
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
相关文章推荐
- C# 连接SQL Server数据库的几种方式--server+data source等方式
- Apache+mod_jk+Tomcat+Memcached win32集群环境搭建
- 跟王老师学MySQL:单表查询
- 8 mysql用户和权限管理
- 7 mysql事务与隔离级别
- 6 mysql备份和还原
- 4 mysql数据类型和SQL模型
- 3 二进制格式安装mysql
- 1.1 mysql初步
- 1 mysql原理
- mysql增删改查语句
- 详解 Spotlight on MySQL监控MySQL服务器
- mysql命令大全
- JDBC使用MYSQL的LOAD DATA LOACAL INFILE和LOAD DATA INFILE
- windows批处理自动修改postgres数据库密码
- CentOS 7安装配置Redis数据库
- MySQL练习题
- Redis学习笔记(十)——过期时间、访问限制与缓存
- oracle语句 trunc()、to_char()、to_date()、add_months()和误删恢复操作
- MySQL5.6 报错1067