好的,所以我有这个查询,它的工作原理:
SELECT games.week, local_team, games.local_goals, visitor_team, games.visitor_goals, winner1
FROM games
JOIN (SELECT local_team = teams.team_name, team_number FROM teams) AS local_team ON games.team_number_loc = local_team.team_number
JOIN (SELECT visitor_team = teams.team_name, team_number FROM teams) AS visitor_team ON games.team_number_vis = visitor_team.team_number
JOIN (
SELECT CASE
WHEN games.local_goals < games.visitor_goals
THEN games.team_number_vis
WHEN games.local_goals > games.visitor_goals
THEN games.team_number_loc
WHEN games.local_goals = games.visitor_goals
THEN null
END AS winner1,
game_number
FROM games)
AS winner1 ON games.game_number = winner1.game_number
但是我需要为赢得比赛的球队名称添加一个专栏,我认为应该这样做:
SELECT games.week, local_team, games.local_goals, visitor_team, games.visitor_goals, winner1, winner2
FROM games
JOIN (SELECT local_team = teams.team_name, team_number FROM teams) AS local_team ON games.team_number_loc = local_team.team_number
JOIN (SELECT visitor_team = teams.team_name, team_number FROM teams) AS visitor_team ON games.team_number_vis = visitor_team.team_number
JOIN (
SELECT CASE
WHEN games.local_goals < games.visitor_goals
THEN games.team_number_vis
WHEN games.local_goals > games.visitor_goals
THEN games.team_number_loc
WHEN games.local_goals = games.visitor_goals
THEN null
END AS winner1,
game_number
FROM games)
AS winner1 ON games.game_number = winner1.game_number
JOIN
(SELECT CASE
WHEN winner1 = teams.team_number
THEN teams.team_name
WHEN winner1 is null
THEN 'no winner'
END AS winner2,
teams.team_number
FROM teams) AS winner2 ON winner2.team_number = winner1
但是当我尝试时,我得到了这个错误:
Msg 207,Level 16,State 1,Line 153 列名称无效&#39; winner1&#39;。
Msg 207,Level 16,State 1,Line 155 列名称无效&#39; winner1&#39;。
我希望的输出与其他位代码完全相同,只是添加了一个获胜团队名称列。
答案 0 :(得分:3)
您不能在其他子查询中使用计算列,而是在最后一个子查询中尝试执行此操作。
您可以尝试以下查询: -
SELECT games.week, local_team, games.local_goals, visitor_team, games.visitor_goals, winner1, winner2 = ISNULL(T.team_name, 'No Winner')
FROM games
JOIN (SELECT local_team = teams.team_name, team_number FROM teams) AS local_team ON games.team_number_loc = local_team.team_number
JOIN (SELECT visitor_team = teams.team_name, team_number FROM teams) AS visitor_team ON games.team_number_vis = visitor_team.team_number
JOIN (
SELECT CASE
WHEN games.local_goals < games.visitor_goals
THEN games.team_number_vis
WHEN games.local_goals > games.visitor_goals
THEN games.team_number_loc
WHEN games.local_goals = games.visitor_goals
THEN null
END AS winner1,
game_number
FROM games)
AS winner1 ON games.game_number = winner1.game_number
LEFT JOIN
teams T ON T.team_number = winner1.winner1