문제

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
도움이 되었습니까?

해결책

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top