转自:
sql中日期查询
今天的所有数据:select * from 表名 where DateDiff(dd,datetime类型字段,getdate())=0昨天的所有数据:select * from 表名 where DateDiff(dd,datetime类型字段,getdate())=17天内的所有数据:select * from 表名 where DateDiff(dd,datetime类型字段,getdate())<=730天内的所有数据:select * from 表名 where DateDiff(dd,datetime类型字段,getdate())<=30本月的所有数据:select * from 表名 where DateDiff(mm,datetime类型字段,getdate())=0本年的所有数据:select * from 表名 where DateDiff(yy,datetime类型字段,getdate())=0 查询今天是今年的第几天: select datepart(dayofyear,getDate())查询今天是本月的第几天:1. select datepart(dd, getDate()) 2.select day(getDate())查询本周的星期一日期是多少 (注意:指定日期不能是周日,如果是周日会计算到下周一去。所以如果是周日要减一天) SELECT DATEADD(wk,DATEDIFF(wk,0,getdate()),0) 查询昨天日期:select convert(char,dateadd(DD,-1,getdate()),111) //111是样式号,(100-114) 查询本月第一天日期:Select DATEADD(mm, DATEDIFF(mm,0,getdate()), 0) as firstday查询本月最后一天日期:Select dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0)) as lastday //修改-3的值会有相应的变化 本月有多少天:select datepart(dd,dateadd(dd,-1,dateadd(mm,1,cast((cast(year(getdate()) as varchar)+'-'+cast(month(getdate()) as varchar)+'-01' ) as datetime )))) 求两个时间段相差几天:select datediff(day,'2012/8/1','2012/8/20') as daysum在指定的日期上±N天:select convert(char,dateadd(dd,1,'2012/8/20'),111) as riqi //输出2012/8/21在指定的日期上±N分钟:select dateadd(mi,-15,getdate()) //查询当前时间15分钟之前的日期在指定日期上加上三天: select dateadd(day,3,'20151105') //输出2015-11-08 00:00:00.000
查询具体某一天
上个月的第一天SELECT DATEADD(mm, DATEDIFF(mm ,0,getdate())-1, 0) //2017-04-01 00:00:00.000上个月的最后一天SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)) //2017-04-30 23:59:59.997本月第一天 SELECT DATEADD(mm, DATEDIFF(mm,0,getdate()), 0) //2017-05-01 00:00:00.000本季度第一天 SELECT DATEADD(qq, DATEDIFF(qq,0,getdate()), 0) //2017-04-01 00:00:00.000本周第一天 SELECT DATEADD(wk, DATEDIFF(wk,0,getdate()), 0) //2017-05-08 00:00:00.000今年第一天 SELECT DATEADD(yy, DATEDIFF(yy,0,getdate()), 0) //2017-01-01 00:00:00.000今天去掉时分秒 SELECT DATEADD(dd, DATEDIFF(dd,0,getdate()), 0) 2017-05-11 00:00:00.000本月最后一天 SELECT DATEADD(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0)) //2017-05-31 23:59:59.997本月第一个星期一 select DATEADD(wk, DATEDIFF(wk,0,dateadd(dd,6-datepart(day,getdate()),getdate())), 0) //2017-05-01 00:00:00.000上个月最后一天 SELECT DATEADD(ms,-3,DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)) //2017-04-30 23:59:59.997去年最后一天 SELECT DATEADD(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)) //2016-12-31 23:59:59.997