Click here to Skip to main content
15,886,864 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 2 tables.

Table 1: Teams

TeamsId__|__TeamName__|_TeamAbv__|__TeamLogo__|
         |            |          |            |
   1     |    Eagles  |   PHI    | eagles.png |
_________|____________|__________|____________|
   2     |    Bills   |   BUF    | bills.png  |
_________|____________|__________|____________|

Continues for 32 teams

Table 2: Schedule

_GameId__|__HomeTeam__|_AwayTeam__|____Week____|
         |            |           |            |
   1     |    1       |     2     |   Week1    |
_________|____________|___________|____________|
   2     |    7       |    12     |   Week1    |
_________|____________|________ __|____________|


The HomeTeam and the AwayTeam numbers are the assigned TeamsId in the Teams Table

I would like to write a query that display the TeamName for each the Home and Away teams in a separate column in 1 table


What I have tried:

Would like to convert this code into 1 table 2 columns:

SELECT Teams.TeamName AS HomeTeam
FROM Teams
JOIN Schedule ON Teams.TeamsId = Schedule.HomeTeam

SELECT Teams.TeamName AS AwayTeam
FROM Teams
JOIN Schedule ON Teams.TeamsId = Schedule.AwayTeam


First Attempt: Error Conversion failed when converting the nvarchar value 'Eagles' to data type int.

SELECT Teams.TeamName AS HomeTeam, Teams.TeamName AS AwayTeam
FROM Teams
JOIN Schedule
ON Teams.TeamName = (SELECT Teams.TeamsId FROM Schedule WHERE Teams.TeamsId = Schedule.AwayTeam)
WHERE Teams.TeamsId = Schedule.HomeTeam
Posted
Updated 19-May-18 10:07am
Comments
PIEBALDconsult 19-May-18 15:56pm    
You don't need a subquery for that, but you'll need to JOIN to the team table twice.
RedDk 19-May-18 15:58pm    
Perhaps the "things" being JOIN'd are of disparate types, yes?

(gambling is a vice)

1 solution

Something like this?

SQL
SELECT ...
FROM Schedule Schd
INNER JOIN Teams Home
ON Schd.HomeTeam = Home.TeamsId
INNER JOIN Teams Away
ON Schd.AwayTeam = Away.TeamsId
 
Share this answer
 
Comments
Commish13 19-May-18 16:56pm    
Thank you, I don't know if you saw my other 2 comments before I deleted them but I figured it out. Thanks for the code it really helped.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900