我有一个数据库“results”表,其中包含以下字段:
game_id, 主队, AWAY_TEAM, HOME_TEAM_SCORE, AWAY_TEAM_SCORE, 结果
目前结果字段可能有3个值,“H”(主队获胜),“A”(客场胜利)或“D”(平局)。现在,为了获得特定团队的所有结果,我做了一个查询,例如“SELECT * FROM results where home_team =”TEAM A“或away_team =”TEAM A“。然后在我的代码中我必须检查是否home_team是TEAM A,结果是H然后是胜利,平局或亏损等。有没有办法我可以在查询中检查所以我会得到一个类似于下面的结果列表
game_id, 主队, AWAY_TEAM, HOME_TEAM_SCORE, AWAY_TEAM_SCORE, 结果(W(胜利),L(失败)或D(平局))
基于所查询的团队。
在网络资源方面苦苦挣扎,感谢任何帮助。
作为参考,它是一个SQLite数据库。
答案 0 :(得分:1)
您可以使用case
来计算SQL中的结果:
select *
, case
when result = 'D' then 'D'
when home_team = @YourTeam and result = 'H' then 'W'
when away_team = @YourTeam and result = 'A' then 'W'
else 'L'
end as Outcome
from YourTable
where home_ream = @YourTeam
or away_team = @YourTeam
答案 1 :(得分:1)
对@Andomar的回答略有改动:))
SELECT
*,
CASE
WHEN result = 'D' THEN 'Draw'
WHEN home_team = @yourTeam AND result = 'H' THEN 'Home Win'
WHEN home_team = @yourTeam AND result = 'A' THEN 'Home Loss'
WHEN result = 'H' THEN 'Away Loss'
ELSE 'Away Win'
END
FROM
YourTable
WHERE
home_team = @yourTeam
OR away_team = @yourTeam
答案 2 :(得分:0)
您没有指定场地(无论是回家还是离开),但似乎是可取的。
home / away和W / L // D组合的结合很容易生成并且易于阅读IMO:
CREATE VIEW YourView
(
game_id, home_team, away_team,
venue, outcome
)
AS
SELECT game_id,
home_team AS your_team,
away_team AS opponent_team,
'H' AS venue, 'W' AS outcome
FROM YourTable
WHERE result = 'H'
UNION
SELECT game_id,
away_team AS your_team,
home_team AS opponent_team,
'A' AS venue, 'W' AS outcome
FROM YourTable
WHERE result = 'A'
UNION
SELECT game_id,
home_team AS your_team,
away_team AS opponent_team,
'H' AS venue, 'L' AS outcome
FROM YourTable
WHERE result = 'A'
UNION
SELECT game_id,
away_team AS your_team,
home_team AS opponent_team,
'A' AS venue, 'L' AS outcome
FROM YourTable
WHERE result = 'H'
UNION
SELECT game_id,
home_team AS your_team,
away_team AS opponent_team,
'H' AS venue, 'D' AS outcome
FROM YourTable
WHERE result = 'D'
UNION
SELECT game_id,
away_team AS your_team,
home_team AS opponent_team,
'A' AS venue, 'D' AS outcome
FROM YourTable
WHERE result = 'A';
SELECT *
FROM YourView
WHERE your_team = @your_team;