简体   繁体   中英

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 . 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM