查询生成列的总和

zzzyeukh  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(178)

我有这个问题

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,

这是一个很长的问题,这是重要的部分。如果需要,可在此处找到完整查询
我正试着在选择中做这样的事情

result_306 + result_2846 AS total_wins,

我无法选择结果\u 306,因为它未定义我尝试执行的操作:

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

但是这个@team1只返回null,这不可能吗?或者有没有一种方法可以对这些列求和。

qoefvg9y

qoefvg9y1#

可以使用子查询:

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

相关问题