查询生成列的总和

时间:2018-08-11 17:11:16

标签: mysql

我有这个查询

SELECT
the_team the_team,
te.name name,
count(CASE WHEN scored > conceded AND opponent = '306'
THEN 1 END) result_306,
count(CASE WHEN scored > conceded AND opponent = '2846'
THEN 1 END) result_2846,

这是一个很长的查询,这是重要的部分。 完整查询found here(如果需要)

我正在尝试在select

中执行类似的操作
result_306 + result_2846 AS total_wins,

我无法选择result_306作为未定义的结果 我尝试这样做:

    @team1:= (count(CASE WHEN scored > conceded AND opponent = '2846'
  THEN 1 END))                                       team2846,

但是这个@ team1只返回Null 这不可能吗?还是有一种方法可以汇总这些列。

1 个答案:

答案 0 :(得分:1)

您可以使用子查询:

SELECT the_team, name,result_306 + result_2846 AS total_wins
FROM (      
  SELECT the_team the_team,
     te.name name,
     count(CASE WHEN scored > conceded AND opponent = '306'
         THEN 1 END) result_306,
     count(CASE WHEN scored > conceded AND opponent = '2846'
        THEN 1 END) result_2846,
   FROM ...) sub