There's probably a better way to do this, but this is what I've done:(note, I have 3 tables involved: Players, Scores, Teams)Here's my main query, which calls a function below to get the team(s)Declare @numRecs intset @numRecs = 50select TOP (@numRecs) WITH TIES rank() over(order by sum(points) desc) rank, first + ' ' + last player, pos, sum(points) pts, dbo.ptsByTeam(id) teamfrom players pjoin scores son p.id = s.playeridgroup by id, first, last, posorder by [rank]
The function:CREATE Function [dbo].[ptsByTeam] ( @playerId int)Returns varchar(255)ASBEGINDeclare @team varchar(32)Declare @points intDeclare @str varchar(255)Declare @tm varchar(32)set @str = ''Declare c Cursorread_onlyfor select t.team, sum(points) pts from scores s join teams t on t.id = s.team where playerid = @playerId group by t.team order by pts descOpen cfetch next from c into @team, @pointsset @tm = @teamwhile @@fetch_status = 0begin if @points <> 0 begin set @str = @str + @team + ' (' + convert(varchar(5), @points) + '), ' end fetch next from c into @team, @pointsendClose cDeallocate cIf len(@str) > 1begin set @str = left(@str, len(@str)-1)endIf charindex(',', @str) = 0begin return @tmendif @str is nullbegin return @tmendReturn ltrim(rtrim(@str))END