I'm not super proud of this as it uses temp tables, but it works. Sometimes the attempt to do everything set-based in just one select hurts my procedural head too much.
This uses Rob's query to find winners and a similar query for losers to populate two temp tables, and then joins them in the final query that produces teamid, wins, losses, and (wins-losses). ordered by the last column.insert into scores select 6,2,3,4 union allselect 6,1,3,4 union allselect 6,1,3,4 union allselect 6,1,3,4 union allselect 7,2,5,4 union allselect 1,2,3,3 union allselect 2,3,4,3 union allselect 1,2,4,3 union allselect 1,3,4,3 union allselect 1,3,4,3 union allselect 1,3,3,4 union allselect 1,3,3,4 union allselect 1,3,3,4declare @wins table (winner int, wins int)declare @losses table (loser int, losses int)insert into @winsSELECT Winner, Count(*) Wins FROM(SELECT CASE WHEN Team_1_Score>Team_2_Score THEN Team_1 ELSE Team_2 END as Winner FROM scores WHERE Team_1_Score<>Team_2_Score) AGROUP BY Winnerinsert into @lossesSELECT Loser, Count(*) Losses FROM(SELECT CASE WHEN Team_1_Score<Team_2_Score THEN Team_1 ELSE Team_2 END as Loser FROM scores WHERE Team_1_Score<>Team_2_Score) AGROUP BY Loserselect w.winner as team ,w.wins as wins ,coalesce(l.losses,0) as losses ,w.wins-coalesce(l.losses,0) as diff from @wins wleft join @losses l on l.loser=w.winnerunion allselect l.loser as team ,0 ,l.losses ,-l.lossesfrom @losses l left join @wins w on l.loser=w.winnerwhere w.winner is nullorder by diff desc
SqlSpec - a fast, cheap, and comprehensive data dictionary generator forSQL Server 2000/2005 and Analysis Server 2005 - http://www.elsasoft.org