------------------------------------------------------------------------------------------------------------
declare @min varchar(4),@max varchar(4), @sqlstr varchar(8000)
set @sqlstr = 'select FItemID'
select @min = min(years), @max = max(years) from #Happen3
while @min <= @max
begin
set @sqlstr = @sqlstr+',
sum(case when years = '+@min +' then(case when Months=1 then (FAmount / FQty)end)end) as Y'+@min +'P1Price,
sum(case when years = '+@min +' then(case when Months=2 then (FAmount / FQty)end)end) as Y'+@min +'P2Price,
sum(case when years = '+@min +' then(case when Months=3 then (FAmount / FQty)end)end) as Y'+@min +'P3Price,
sum(case when years = '+@min +' then(case when Months=4 then (FAmount / FQty)end)end) as Y'+@min +'P4Price,
sum(case when years = '+@min +' then(case when Months=5 then (FAmount / FQty)end)end) as Y'+@min +'P5Price,
sum(case when years = '+@min +' then(case when Months=6 then (FAmount / FQty)end)end) as Y'+@min +'P6Price,
sum(case when years = '+@min +' then(case when Months=7 then (FAmount / FQty)end)end) as Y'+@min +'P7Price,
sum(case when years = '+@min +' then(case when Months=8 then (FAmount / FQty)end)end) as Y'+@min +'P8Price,
sum(case when years = '+@min +' then(case when Months=9 then (FAmount / FQty)end)end) as Y'+@min +'P9Price,
sum(case when years = '+@min +' then(case when Months=10 then (FAmount / FQty)end)end) as Y'+@min +'P10Price,
sum(case when years = '+@min +' then(case when Months=11 then (FAmount / FQty)end)end) as Y'+@min +'P11Price,
sum(case when years = '+@min +' then(case when Months=12 then (FAmount / FQty)end)end) as Y'+@min +'P12Price'
set @min = @min+1
end
set @sqlstr = @sqlstr +' into ##Happen4 from #Happen3 where Not(FQty=0) group by FItemID'
exec(@sqlstr)