尝试使用一列来汇总来自UNION的值

时间:2018-03-25 18:19:17

标签: sql sum union

我有一个简单的数据库,其中包含有关游戏和分数的信息,如下所示:

Tournament Black_ID    White_ID    Black_Score    White_Score
47          81          54          1              1
-------------------------------------------------------------
47          81          65          1              1
-------------------------------------------------------------
47          54          81          2              0
-------------------------------------------------------------
47          44          81          0              2
-------------------------------------------------------------
..
-------------------------------------------------------------
...
-------------------------------------------------------------

如果一名球员获胜,他们获得2分,平局意味着每分1分,而损失意味着0分。

我试图获得第47场比赛中球员81收到的所有积分。

我尝试了以下操作:

SELECT SUM(Score) FROM(
    SELECT White_Score as Score FROM Table
    WHERE Tournament = 47 AND White_ID = 81
    UNION ALL
    Select Black_Score FROM Table
    WHERE Tournament = 47 AND Black_ID = 81
)

但它在最后一行的'(行尾)附近给出了语法错误。

如果我删除SUM(Score)部分,请执行以下操作:

SELECT White_Score as Score FROM Table
WHERE Tournament = 47 AND White_ID = 81
UNION ALL
Select Black_Score FROM Table
WHERE Tournament = 47 AND Black_ID = 81

它给了我一张这样的表格:

Score
-----
1
-----
1
-----
0
-----
2
-----

我似乎找不到如何总结的解决方案。

2 个答案:

答案 0 :(得分:0)

您应该添加别名:

SELECT SUM(Score) FROM(
SELECT White_Score as Score FROM Table
WHERE Tournament = 47 AND White_ID = 81
UNION ALL
Select Black_Score FROM Table
WHERE Tournament = 47 AND Black_ID = 81
) sub  --here

答案 1 :(得分:0)

对于这个简单的案例,您不需要UNION和子查询。您可以改为使用条件聚合:

SELECT SUM(CASE WHEN White_ID = 81 THEN White_Score END)
     + SUM(CASE WHEN Black_ID = 81 THEN Black_Score END) AS Score
FROM Table
WHERE Tournament = 47