[英]while loop in t-sql with start and end year
I want to loop through the years and get the counts for each month on each year using below while loop . 我想循环使用这些年,并使用下面的while循环获取每年每个月的计数。 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. 我认为你的
WHILE
循环搞砸了。 You are declaring @end_year = 2015
and then saying WHILE (@end_year < 2015)
. 你宣布
@end_year = 2015
然后说WHILE (@end_year < 2015)
。 I think you meant WHILE (@loop_year < @end_year)
. 我想你的意思是
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.