Find the Same day of Previous Year Given by Current Year Date in SQL Server -
i working sql server, scenario find out same day's date of previous year of today's day.
suppose 2014-03-06 today date , day thursday want find same day in previous lies in same week .which 2013-03-07
can body help? here have written:
declare @datefrom datetime declare @dateto datetime set @datefrom = '2014-01-01' set @dateto = '2014-02-10' declare @count int set @count = datediff(day, @datefrom, @dateto) create table #current_year /*this year*/ ( [date] datetime , weeknum int, [day] varchar(20), data int ) create table #last_year /*this year -1*/ ( [date] datetime , weeknum int, [day] varchar(20), data int ) while ( @count > 0 ) begin insert #current_year values ( convert(varchar(10), @datefrom, 101), datepart(week,@datefrom), datename(weekday, @datefrom),@count) insert #last_year values ( convert(varchar(10), dateadd(year, -1, @datefrom), 101), datepart(week,dateadd(year,1,@datefrom)), datename(weekday, dateadd(year, -1, @datefrom)),@count) set @datefrom = dateadd(day, 1, @datefrom) set @count = @count - 1 end select * #current_year select * #last_year select convert(varchar(10),#current_year.[date],111) cydate, --isnull(convert(varchar(10),#last_year.[date],111) ,/*convert(varchar(10),dateadd(dd, 1, dateadd(yy, -1, #current_year.date)),111)*/) lydate --convert(varchar(10),#last_year.[date],111) lydate coalesce(convert(varchar(10),#last_year.[date],111) ,dateadd(dd, 1, dateadd(yy, -1, #current_year.date))) lydate, #current_year.data cd, #last_year.data ld #current_year --left join #last_year on #last_year.weeknum = #current_year.weeknum -- , #last_year.[day] = #current_year.[day] left join #last_year on #last_year.weeknum = datepart(wk, getdate()) drop table #current_year drop table #last_year
here output:
here output after adding solution, in left join excludes (null) data of previous year
basically need find difference in days between same dates in , previous years, understand "day difference" mod 7, , sum date in previous year:
declare @now datetime set @now = '2014-03-06' select cast (dateadd(year, -1, @now) + (cast (@now int) - cast (dateadd(year, -1, @now) int)) % 7 date)
returns
2013-03-07
Comments
Post a Comment