Gideon
Gideon

Reputation: 2014

Stuck with T-SQL Query

I'm having big troubles with a more complicated (or my mind makes it so) SQL query. Ill try to explain as best as I can what is needed.

This is how it looks like essentially: https://i.sstatic.net/My5uD.png

The idea is that there will be sport games where kids team up with pro's and they have a tournament. Now everything works fine untill I get to the score part.

I need a query that return a game's outcome in 4 colomns: winchildname, winproname, losechildname, loseproname.

This way its easy to display in my C# project. If i use this query:

SELECT * FROM Games WHERE g_win = 1 OR g_lose = 1

This returns every game played by child with the k_id 1 but the outcome is in ints instead actual text. I know how to inner join 1 int so it becomes text, but not 2. Because g_win and g_lose are both a k_id out of the child table.

Is there someone that can give me a hint, because I feel that im overthinking this big time.

Upvotes: 1

Views: 79

Answers (1)

Lucero
Lucero

Reputation: 60190

You can join multiple times on the same table by giving the table an alias:

WITH Names AS (
  SELECT k_id AS id, k_name, p_name
  FROM Child
  JOIN Pro ON k_pro = p_id
)
SELECT win.k_name AS win_k_name, win.p_name AS win_p_name, lose.k_name AS win_k_name, lose.p_name AS lose_p_name
FROM Games
JOIN Names AS win ON g_win = win.id
JOIN Names AS lose ON g_lose = lose.id

Upvotes: 1

Related Questions