当前时间 select getdate() 当前时间周的起始日期(以周一为例)select DATEADD(week,DATEDIFF(week,0,getdate()),0) 上周起始:select dateadd(week,-1,DATEADD(week,DATEDIFF(week,0,getdate()),0)) 上上周起始:select dateadd(week,-2,DATEADD(week,DATEDIFF(week,0,getdate()),0)) 上上上周起始:select dateadd(week,-3,DATEADD(week,DATEDIFF(week,0,getdate()),0))
以下是周
--上周日(日期格式) SELECT DATEADD(wk, DATEDIFF(wk,0,DATEADD(dd, -7, getdate()) ), -1) --上周六(日期格式) SELECT DATEADD(wk, DATEDIFF(wk,0,DATEADD(dd, -7, getdate()) ), 5)
--本周日(字符串格式) SELECT CONVERT(nvarchar(10), DATEADD(wk, DATEDIFF(wk,0,DATEADD(dd, -1, getdate()) ), -1),121) --本周六(字符串格式) SELECT CONVERT(nvarchar(10), DATEADD(wk, DATEDIFF(wk,0,DATEADD(dd, -1, getdate()) ), 5),121)
--下周日(字符串格式) SELECT CONVERT(nvarchar(10), DATEADD(wk, DATEDIFF(wk,0,DATEADD(dd, 7, getdate()) ), -1),121) --下周六(字符串格式) SELECT CONVERT(nvarchar(10), DATEADD(wk, DATEDIFF(wk,0,DATEADD(dd, 7, getdate()) ), 5),121)
以下是月
--上个月第一天 select dateadd(dd,-day(dateadd(month,-1,getdate()))+1,dateadd(month,-1,getdate())) --上个月最后一天 select dateadd(dd,-day(getdate()),getdate())
--本月第一天 select dateadd(dd,-day(getdate())+1,getdate()) --本月最后一天 select dateadd(dd,-day(getdate()),dateadd(m,1,getdate()))
--下个月第一天 select dateadd(dd,-day(dateadd(month,1,getdate()))+1,dateadd(month,1,getdate())) --下个月最后一天 select dateadd(dd,-day(dateadd(month,2,getdate())),dateadd(month,2,getdate())) declare _LastWeekStartTime date; -- 上周开始时间 declare _LastWeekEndTime date; -- 上周结束时间 -- 因系统为星期日为每星期第一天 所以需要减1 set @A = date_add(curdate(), interval -1 day); -- 算出本周星期一的日期 set @B = subdate( @A,date_format(@A,'%w')-1); -- 因系统为星期日为每星期第一天 所以需要 减2 获取上星期最后一天(上星期星期六) set @C = date_add(@B, interval -2 day); set _LastWeekStartTime = ( subdate( @C,date_format( @C,'%w')-1)); set _LastWeekEndTime = ( date_add(subdate( @C,date_format( @C,'%w')-1), interval 6 day));