如何在两个连续的列上创建一个指示匹配获胜者的新列?

时间:2014-10-22 10:48:02

标签: mysql

假设我们有一个像这样的表:

MATCH_ID TEAM_ID   GOAL
123       1        4
123       2        1
126       1        1
126       3        2

我尝试创建一个新列,指示该匹配的结果(winner = 1,looser = -1,draw = 0)

MATCH_ID TEAM_ID   GOAL   RESULT
123       1        4      1
123       2        1      -1
126       1        1      -1
126       3        2      1

鉴于这些表结构,MySQL脚本将计算哪个结果列?

1 个答案:

答案 0 :(得分:1)

SELECT x.*
     , CASE WHEN y.goals > x.goals THEN -1 
            WHEN y.goals < x.goals THEN 1 
            ELSE 0 END result 
  FROM my_table x 
  JOIN my_table y 
    ON y.match_id = x.match_id 
   AND y.team_id <> x.team_id 
 ORDER BY match_id,team_id;