sql server - Calculate percentage variation of values of current year and previous year for the same period in SQL -
i have data in database contains values corresponding each date. need calculate percentage variation in count of values of current year , previous year same period. period mean january first current date in year. how in sql. using sql server. table structure this.
id | date ------------------------- 1xxxxx | 01-01-2014 2xxxxx | 14-01-2014 3xxxxx | 01-03-2014 4xxxxx | 12-10-2014 5xxxxx | 01-12-2014 6xxxxx | 02-03-2015 7xxxxx | 04-03-2015 8xxxxx | 11-04-2015
try this:
declare @today date, @prev_year_today date, @this_year_count int, @prev_year_count int, @percentage_change float set @today = getdate() set @prev_year_today = dateadd(year, -1, @today) select @this_year_count = count(*) some_values year <= @today , datepart(year, year) = datepart(year, @today) select @prev_year_count = count(*) some_values year <= @prev_year_today , datepart(year, year) = datepart(year, @prev_year_today) set @percentage_change = 100.00 * (@this_year_count - @prev_year_count) / @prev_year_count select @percentage_change
Comments
Post a Comment