If tbl_page is changed to (pageid, matchid) with 100 rows per page then the query would be easy. Can you change the table structure? If not you'll have to transform the table in the query using UNPIVOT.Here is an example with 2 pages of 3 matches each:;with tbl_page (pageid, match1, match2, match3)as( select 1, 1, 2, 3 union all select 2, 4, 5, 6),tbl_team(teamID, teamName, leagueID)as ( select 1, 'team1', 100 union all select 2, 'team2', 100 union all select 3, 'team3', 100 union all select 4, 'team4', 100 union all select 5, 'team5', 100 union all select 6, 'team6', 100 union all select 7, 'team7', 100 union all select 8, 'team8', 100 union all select 9, 'team9', 100 union all select 10, 'team10', 100 union all select 11, 'team11', 100 union all select 12, 'team12', 100 ),tbl_league(leagueID, leagueName) as ( select 100, 'League100'),tbl_match(matchID, leagueID, guestTeamID, hostTeamID)as ( select 1, 100, 1, 7 union all select 2, 100, 2, 8 union all select 3, 100, 3, 9 union all select 4, 100, 4, 10 union all select 5, 100, 5, 11 union all select 6, 100, 6, 12 )select p.pageid ,p.matchid ,tg.teamName as [guestTeam] ,th.teamName as [hostTeam] ,l.leagueNamefrom tbl_league linner join tbl_match m on m.leagueID = l.leagueIDinner join tbl_team tg on tg.teamid = m.guestTeamIDinner join tbl_team th on th.teamid = m.hostTeamIDinner join ( --unpivot the matches by page select u.pageid ,u.matchID from tbl_page unpivot (matchID for match in ([match1], [match2], [match3])) as u ) p on p.matchid = m.matchidOUTPUT:pageid matchid guestTeam hostTeam leagueName----------- ----------- --------- -------- ----------1 1 team1 team7 League1001 2 team2 team8 League1001 3 team3 team9 League1002 4 team4 team10 League1002 5 team5 team11 League1002 6 team6 team12 League100
Be One with the OptimizerTG