sql server 通过 sql查询今天、本周、上周、本月、上月、今年、去年的时间范围
因为经常用到,做个笔记记录下
select
/*今天*/
convert(varchar(10),CAST(GETDATE() AS DATE),120),
convert(varchar(10),CAST(GETDATE() AS DATE),120),
/*本周*/
convert(varchar(10),DATEADD(wk, DATEDIFF(wk, 7, GETDATE())+1, 0),120),
convert(varchar(10),DATEADD(DAY, 6, DATEADD(wk, DATEDIFF(wk, 7, GETDATE())+1, 0)),120),
/*上周*/
convert(varchar(10),DATEADD(wk, DATEDIFF(wk, 7, GETDATE()), 0),120) ,
convert(varchar(10),DATEADD(DAY, 6, DATEADD(wk, DATEDIFF(wk, 7, GETDATE()), 0)),120),
/*本月*/
convert(varchar(10),DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1),120) ,
convert(varchar(10),EOMONTH(GETDATE()),120) ,
/*上月*/
convert(varchar(10),DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1, 0),120) ,
convert(varchar(10),EOMONTH(DATEADD(MONTH, -1, GETDATE())),120),
/*今年*/
convert(varchar(10),DATEFROMPARTS(YEAR(GETDATE()), 1, 1),120),
convert(varchar(10),DATEFROMPARTS(YEAR(GETDATE()), 12, 31),120) ,
/*去年*/
convert(varchar(10),DATEFROMPARTS(YEAR(GETDATE()) - 1, 1, 1),120),
convert(varchar(10),DATEFROMPARTS(YEAR(GETDATE()) - 1, 12, 31),120)