通过唯一ID对单独列中的两个数字求和

时间:2016-06-18 00:48:48

标签: mysql

我有四列 home_id_1 home_score_1 away_id_1 away_score_1

我试图总结home_score_1 AND away_score_1的得分,例如,home_id_1 AND away_id_1列都返回1。

有人可以帮忙,因为我无法解决这个问题。

我最接近的是:

SELECT home_score_1 AS home FROM scores
WHERE home_id_1 = 1
UNION
SELECT away_score_1 AS home FROM scores
WHERE away_id_1 = 1

但这仅提供两个单独的条目,而不是总和。

home_id_1 home_score_1 away_id_1 away_score_1
1:3:2:8
2:4:1:7

抱歉,我不知道如何正确制作上述列格式。因此,寻找显示1的主/客户ID,并从分数列中返回与该ID相对的总和,总计为3 + 7。

感谢。

1 个答案:

答案 0 :(得分:0)

将您的代码包装为子查询,它应该是工作

    SELECT SUM(a.home) as home FROM
    ( 
      SELECT home_score_1 as home FROM scores
      WHERE home_id_1 = 1
      UNION
      SELECT away_score_1 AS home FROM scores
      WHERE away_id_1 = 1 
     ) a