Author |
Topic |
matkwan
Starting Member
36 Posts |
Posted - 2007-04-24 : 11:50:11
|
Hi, this is my table:PlayerID, SportID, Scores1, 1, 52, 1, 11, 5, 52, 5, 31, 1, 52, 1, 11, 2, 12, 2, 5I need a query to return me the top player for each sport with the total score for each sport, eg:PlayerID, SportID, Scores1, 1, 102, 2, 51, 5, 5I have tried:SelectPlayerID, SportID, Sum(Scores) as SumScoresFromUserSportScoresGroup ByPlayerID, SportIDbut not right.Is it possible to achieve this using SQL ?Matt |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-04-24 : 12:04:55
|
This is what you want ?declare @table table( PlayerID int, SportID int, Scores int)insert into @tableselect 1, 1, 5 union allselect 2, 1, 1 union allselect 1, 5, 5 union allselect 2, 5, 3 union allselect 1, 1, 5 union allselect 2, 1, 1 union allselect 1, 2, 1 union allselect 2, 2, 5select PlayerID, SportID, Scores = sum(Scores)from @table twhere PlayerID in (select top 1 PlayerID from @table x where x.SportID = t.SportID group by PlayerID order by sum(Scores) desc)group by PlayerID, SportID/*PlayerID SportID Scores ----------- ----------- ----------- 1 1 101 5 52 2 5*/ KH |
 |
|
mattyblah
Starting Member
49 Posts |
Posted - 2007-04-24 : 12:07:58
|
do you have to do it with one query? if so, try this:select playerid, t1.sportid, t1.score from (select playerid, sportid, sum(scores) as score from table group by playerid, sportid) t1 inner join (select sportid, max(score) as score from (select playerid, sportid, sum(scores) as score from table group by playerid, sportid) t group by sportid) t2 on t1.sportid = t2.sportid and t1.score = t2.score order by t1.sportid ascI'm sure someone could provide something cleaner...Edit: Wow, the above one is much cleaner and more efficient. |
 |
|
matkwan
Starting Member
36 Posts |
Posted - 2007-04-24 : 12:25:47
|
Thanks guys. I prefer the 1 query solution by MattyBlah. |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-04-24 : 12:47:51
|
Look at the execution plans. Which is more efficient? Khtan also wrote a 1-query solutionquote:
select PlayerID, SportID, Scores = sum(Scores)from @table twhere PlayerID in (select top 1 PlayerID from @table x where x.SportID = t.SportID group by PlayerID order by sum(Scores) desc)group by PlayerID, SportID
Peter LarssonHelsingborg, Sweden |
 |
|
mattyblah
Starting Member
49 Posts |
Posted - 2007-04-24 : 17:25:31
|
I was gonna say. Looks like kh's should be more efficient and it's also a 1-query (relative term) solution. Just substitute your table for @table. |
 |
|
|
|
|