Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
davidshq
Posting Yak Master
119 Posts |
Posted - 2005-12-03 : 12:36:07
|
| I want to create a job that averages the results from one table and then inserts them into another table. I've got the average command down fine:update game set Popularity = (select avg(Popularity) from GamePopularity Where gID=2) Where ID=2As you can see it inserts and averages, the problem is I have say three hundred records in this table right now, so I really need a While loop that cycles through each record, rather than me manually entering the ID like I did above.(Pseudo-Code)select ID from gameFor Each ID in Gameupdate game set Popularity = (select avg(Popularity) from GamePopularity Where gID=CurrentID) Where ID=CurrentIDNextDavid- http://www.gamesecretary.com/- http://www.thehungersite.com/- http://www.grid.org/ |
|
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2005-12-03 : 12:41:25
|
| No need for a loop at all:UPDATE A SET Popularity=B.Avg_PopularityFROM Game A INNER JOIN (SELECT ID, Avg(Popularity) Avg_Popularity FROM GamePopularity GROUP BY ID) B ON A.ID=B.ID |
 |
|
|
davidshq
Posting Yak Master
119 Posts |
Posted - 2005-12-03 : 13:03:08
|
| Thanks. I have one question. My data looks something like this:Game Table:ID - Title - Popularity1 - Kickball - 82 - Dodgeball - 93 - Fooseball - 5GamePopularity Table:ID - uID - gID - Popularity1 - JamesG - 2 - 42 - WilliamC - 1 - 83 - MarthaE - 1 - 10As you can see, just b/c the ID in GamePopularity is the same as the ID in Game doesn't make the two about the same Game. Rather, this will generally not be true. Rather gID in GamePopularity is equal to the referenced Game in the Game table.In your example code you said to GROUP BY ID and to JOIN ON ID...But don't I want them to GROUP BY gID and JOIN ON A.ID=B.gID?Thanks again for your help.David.- http://www.gamesecretary.com/- http://www.thehungersite.com/- http://www.grid.org/ |
 |
|
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2005-12-03 : 13:21:35
|
| Yes, that's correct. |
 |
|
|
davidshq
Posting Yak Master
119 Posts |
|
|
|
|
|