高级查询-Select,条件求和和return累加值

Advance query - Select, sum on condition and return the accumulated value

一位用户预测给定比赛的球队获胜者。根据预测的球队以及预测是否正确,根据所选球队的赔率给予不同的分数。考虑以下两个 SQL 表及其字段。

如果锦标赛 ID 30 的预测正确(意味着 predictions.team_id 需要与 matches.match_winner 匹配),我想要一个汇总所有用户赔率的查询。最终结果应该如下所示

Matthew预测正确匹配5和7(赔率3.4 + 2.4),总分5.8分。

Neville 预测正确匹配 7 和 9(赔率 2.4 + 2.0),总计 4.4 分

使用带有条件 SUM 的聚合查询,例如:

SELECT
    p.username,
    SUM(CASE WHEN m.match_winner = m.team_a THEN m.team_a_odds ELSE m.team_b_odds END)
FROM 
    predictions p
    INNER JOIN matches m
        ON p.match_id = m.id AND p.team_id = m.match_winner
WHERE p.tournament_id = 30
GROUP BY p.username
SELECT
  USERNAME,
  SUM(IF(CASE WHEN MATCH_WINNER = TEAM_A, TEAM_A_ODDS, TEAM_B_ODDS))
FROM
  PREDICTIONS
INNER JOIN MATCHES
  ON MATCH_ID = MATCHES.ID AND 
    TEAM_ID = MATCH_WINNER
GROUP BY USERNAME;

但是由于Neville predicted correctly match 7 and 9 (odds 2.4 + 2.0), total 4.4 points不满足...

SELECT
  USERNAME,
  SUM( TEAM_B_ODDS)
FROM
  PREDICTIONS
INNER JOIN MATCHES
  ON MATCH_ID = MATCHES.ID AND 
    TEAM_ID = MATCH_WINNER
GROUP BY USERNAME;

OP 总是求和 TEAM_B_ODDS

尽管我认为 OP 评估 Naville 大小写错误。