提前查询-选择,求和并返回累加值

时间:2019-01-05 11:58:14

标签: mysql sql query-performance

用户预测给定比赛的团队冠军。根据所预测的团队以及预测是否正确,将根据所选团队的赔率来授予不同的分数。请考虑以下两个SQL表及其字段。

Matches table

enter image description here 如果查询ID为30的预测正确(意味着predictions.team_id必须与matches.match_winner匹配),我想查询一个汇总所有用户赔率的查询。最终结果应该像这样

enter image description here

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

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

2 个答案:

答案 0 :(得分:2)

使用条件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

答案 1 :(得分:1)

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的情况是错误的。