查询返回杯子表中的赢家和输家?

时间:2015-10-28 04:34:27

标签: mysql sql

我有一个具有此架构的表

year,team1,team2,winner

2010,12,13,12

我想以此形式返回数据

year,winner,runner-up

可以使用sql查询吗?

4 个答案:

答案 0 :(得分:2)

想出框

  

获胜者 - 获胜team_id = 0
      0 - 未获胜的team_id = -team_id

SELECT year, winner, ABS(winner - team1 - team2) AS `runner up`
FROM YourTable

SQLFiddle

答案 1 :(得分:1)

尝试使用以下查询。肉与土豆是CASE声明,对于原始表中的每个记录,它将选择获胜者的团队作为亚军。

SELECT year, winner, CASE WHEN team1 = winner THEN team2 ELSE team1 END AS runnerUp
FROM teamStats

点击以下链接查看正在运行的示例:

SQLFiddle

答案 2 :(得分:0)

只需使用CASE表达式。

我们已经从winner专栏了解获奖团队。所以runner-up将是另一个。因此,我们可以使用case语句返回不在winner列中的团队..

<强>查询

SELECT `year`, winner,
    CASE winner WHEN team1 THEN team2 ELSE team1 END AS `runner-up`
FROM tblMatches;

SQL Fiddle

答案 3 :(得分:0)

使用VIEW创建SELECT,它将作为您的临时表格,并将返回包含所需详细信息的表格。
CREATE VIEW GET_WINNER as SELECT year, winner, ABS(winner - team1 - team2) AS runner up FROM YourTable