如何区分两个求和查询

时间:2014-04-23 11:32:32

标签: mysql sql

我必须计算足球队的目标差异。 基本上是: (goalScoredAtHome + goalsScoredAway) - (goalConciededAtHome + goalsConciededAway) 一切都保存在一个表中:

homeTeam | awayTeam | goalsHome | goalsAway
  USA    |  Poland  |     2     |    0
 Poland  |   USA    |     3     |    1

这就是我有4个单独的查询:

(select sum(goalsHome) as GoalsScoredHome from game where home = 'USA' 
+
select sum(goalsAway) as GoalsScoredAway from game where away = 'USA')
-
(select sum(goalsAway) as GoalsConciededHome from game where home = 'USA'
+
select sum(goalsHome) as GoalsConciededAway from game where away = 'USA')

有没有办法在一个查询中执行此操作?

2 个答案:

答案 0 :(得分:5)

您的查询的直接翻译使用条件聚合:

select (sum(case when home = 'USA' then goalsHome else 0 end) +
        sum(case when away = 'USA' then goalsAway else 0 end)
       ) -
       (sum(case when home = 'USA' then goalsAway else 0 end) +
        sum(case when away = 'USA' then goalsHome else 0 end)
       )
from game;

您可以将其简化为:

select (sum(case when home = 'USA' then goalsHome - goalsAway else 0 end) +
        sum(case when away = 'USA' then goalsAway - goalsHome else 0 end)
       )
from game;

答案 1 :(得分:1)

您可以执行以下操作

select sum(gs-gs) as GoalScore from(
  select sum(GoalsScore1) as gs from (
    select sum(goalsHome) as GoalsScore1 from game where homeTeam = 'USA' union all select sum(goalsAway) as GoalsScore1 from game where awayTeam = 'USA'
  )gs1 union all
  select sum(GoalsScore2) as gs from (
    select sum(goalsHome) as GoalsScore2 from game where homeTeam = 'USA' union all select sum(goalsAway) as GoalsScore2 from game where awayTeam = 'USA'
  )gs2
)gs3