Question

I want to loop through the years and get the counts for each month on each year using below while loop . How can I achieve this by limited the number of years.

declare @start_year int=1999
declare @loop_year int
declare @end_year int=2015

WHILE (@end_year <2015)
BEGIN

Select    count(*) as rows,month(create_datetime) as month, year(create_datetime) as year
FROM      [table_name]
WHERE     year(create_datetime) =@loop_year
GROUP BY  month(create_datetime),year(create_datetime)
set @loop_year=@start_year+1
END
Was it helpful?

Solution

I think your WHILE loop is messed up. You are declaring @end_year = 2015 and then saying WHILE (@end_year < 2015). I think you meant WHILE (@loop_year < @end_year).

With that said, there is no reason to use a loop for this particular case. This should accomplish the same results:

Select count(*) as rows,
    month(create_datetime) as month, 
    year(create_datetime) as year
FROM      [table_name]
WHERE     year(create_datetime) BETWEEN 1999 AND 2014
GROUP BY  month(create_datetime), year(create_datetime)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top