我希望循环使用这些年,并使用下面的while循环获取每年每个月的计数。如何通过限制年数来实现这一目标。
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
答案 0 :(得分:2)
我认为你的WHILE
循环搞砸了。您宣布@end_year = 2015
然后说WHILE (@end_year < 2015)
。我认为你的意思是WHILE (@loop_year < @end_year)
。
话虽如此,没有理由对这种特殊情况使用循环。这应该可以实现相同的结果:
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)