Jan 2, 2018

get weekly data (Lastweek, Thisweek and Nextweek) in sql server



declare @TodaysDate datetime;
set @TodaysDate = getdate();

select convert(varchar(20), dateadd(wk, datediff(wk, 0, @TodaysDate) -1, 0), 107) LastWeekStart
select convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate), -1), 107) LastWeekEnd

select convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate), 0), 107) ThisWeekStart
select convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate) +1, -1),107) ThisWeekEnd

select convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate) + 1, 0),107) NextWeekStart
select convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate) +2 , -1),107) NextWeekEnd


OR || Required date format - Monthname dd, yyyy


declare @TodaysDate datetime;
set @TodaysDate = getdate();
-- with this (December 31, 2017) date format
select datename(mm, convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate)-1, 0), 107))
+' '+ replace(convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate)-1, 0), 107),
left(convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate)-1, 0), 107),4),'') LastWeekStart

select datename(mm, convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate), -1), 107))
+' '+ replace(convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate), -1), 107) ,
left(convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate), -1), 107) ,4),'')  LastWeekEnd

select datename(mm,convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate), 0), 107))
+' '+ replace(convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate), 0), 107),
left(convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate), 0), 107), 4), '') ThisWeekStart

select datename(mm,convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate) +1, -1),107))
+' '+ replace(convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate) +1, -1),107),
left(convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate) +1, -1),107),4),'') ThisWeekEnd

select datename(mm,convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate) + 1, 0),107))
+' '+ replace(convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate) + 1, 0),107),
left(convert(varchar(15), dateadd(wk, datediff(wk, 0, @TodaysDate) + 1, 0),107),4),'') NextWeekStart

select datename(mm,convert(varchar(15), dateadd(wk,datediff(wk, 0, @TodaysDate) +2 , -1),107))
+' '+ replace(convert(varchar(15), dateadd(wk,datediff(wk, 0, @TodaysDate) +2 , -1),107),

left(convert(varchar(15), dateadd(wk,datediff(wk, 0, @TodaysDate) +2 , -1),107),4),'') NextWeekEnd


Result :







No comments:

Post a Comment