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 |
|
roblasch
Starting Member
10 Posts |
Posted - 2002-09-01 : 12:52:20
|
| I have found a few solutions to this question, but none seem to work in this instance. I have a search query that returns these results( they could be in a temp table or derived) Weight AdvertiserID CategoryID10 1 16 1 28 1 34 1 110 2 18 2 2Any of the three columns can be any value. I need to total the weight for each categoryID,AdvertiserID and then select the top record for each advertiserID. The column I need to access is the CategoryID. In other words, the search returns multiple categories for each advertiser and I need to select the one with the highest weight.Thanks, Robert Lasch |
|
|
VyasKN
SQL Server MVP & SQLTeam MVY
313 Posts |
Posted - 2002-09-01 : 17:15:53
|
| I will use a view to simplify the query. If you don't like views, you can substitute it with a derived table, but it only makes the query look messy. Anyways, here's my solution:--Create the view firstCREATE VIEW AdsV ASSELECT AdvertiserID, CategoryID, SUM(Weight) AS WeightFROM AdsGROUP BY AdvertiserID, CategoryID--Now query the view --to get the highest ranked category --for each advertiserSELECT v1.AdvertiserID, v1.CategoryID, v1.WeightFROM AdsV v1JOIN(SELECT AdvertiserID, MAX(Weight) AS WeightFROM AdsVGROUP BY AdvertiserID) AS v2ON v1.AdvertiserID = v2.AdvertiserID AND v1.Weight = v2.Weight--HTH,Vyashttp://vyaskn.tripod.com |
 |
|
|
|
|
|
|
|