rogerzebra
Technical User
good evening folks,
I have an issue with a loop and I was hoping for some input from any of you guys, that would be greately appreciated. I'm trying to update an empty tmp column with the average value of a product for each year, one year at the time. This should be fairly simple but, I can't get around this issue and apparently need your input.
First it was a while ago I was using loops so that might be the reason, second I tried to use a set based statement due to some suggestions on this forum but, got nasty errors indicating that it doesn't seems to like aggregates as a set value. Unfortunately, I'm not at work so I can't provide you with my original query but, hopefully you can tell from my improvised two minute code, what I'm trying to acchive. I just want to get a ruff idea of how to deal with aggregates and calculations in an insert loop and insert one row by one.
Thanks
/r
I have an issue with a loop and I was hoping for some input from any of you guys, that would be greately appreciated. I'm trying to update an empty tmp column with the average value of a product for each year, one year at the time. This should be fairly simple but, I can't get around this issue and apparently need your input.
First it was a while ago I was using loops so that might be the reason, second I tried to use a set based statement due to some suggestions on this forum but, got nasty errors indicating that it doesn't seems to like aggregates as a set value. Unfortunately, I'm not at work so I can't provide you with my original query but, hopefully you can tell from my improvised two minute code, what I'm trying to acchive. I just want to get a ruff idea of how to deal with aggregates and calculations in an insert loop and insert one row by one.
Thanks
/r
Code:
declare @Id int,
@AvgValue money,
@r1 int,
@r2 int,
set @r1 = (select max(id) from tmp)
set @r2 = (select avg(retail)/max(retail) from tmp)
create table tmp (Id int, AvgValue money)
set @Id = 0
while @Id < @r1
begin
set @value = @r2 + 1
insert into tmp values(@Id, @AvgValue )
end
select * from tmp
drop table tmp