SQLite的总和

时间:2018-10-16 14:44:39

标签: sqlite

假设我有两个看起来像这样的表:

Games:
| AwayTeam  | HomeTeam     | AwayPoints | HomePoints |
------------------------------------------------------
| Aardvarks | Bobcats      | 2          | 1          |
| Bobcats   | Caterpillars | 20         | 10         |
| Aardvarks | Caterpillars | 200        | 100        |

Teams:
| Name         | 
----------------
| Aardvarks    | 
| Bobcats      |
| Caterpillars |

我如何得出如下所示的结果?

| Name         | TotalPoints |
------------------------------
| Aardvarks    | 202         |
| Bobcats      |  21         | 
| Caterpillars | 110         |

我认为我真正的问题是如何在SQL中将语句拼接在一起。这两个语句分别工作良好:

SELECT SUM ( AwayPoints ) 
FROM   Games 
WHERE  AwayTeam='Bobcats';

SELECT SUM ( HomePoints ) 
FROM   Games 
WHERE  HomeTeam='Bobcats';

如果我想将两个compound operator语句拼接在一起,我怀疑我需要SELECT。然后将该语句传递到下面的聚合表达式中:

SELECT   Name, SUM( aggregate_expression ) 
AS       'TotalPoints' 
FROM     Teams 
GROUP BY Name;

如果我不得不将它们放在一起,我想我最终会得到这样的东西:

SELECT   Name, SUM (
    SELECT SUM ( AwayPoints ) 
    FROM   Games 
    WHERE  AwayTeam=Name 
  UNION 
    SELECT SUM ( HomePoints )
    FROM   Games 
    WHERE  HomeTeam=Name
)
AS       'TotalPoints' 
FROM     Teams 
GROUP BY Name;

但是,由于SELECT SUM ( SELECT ...完全无效,因此无效

1 个答案:

答案 0 :(得分:1)

使用UNION ALL

SELECT team, SUM(points)
FROM (
  SELECT HomeTeam AS team, SUM(HomePoints) AS points
  FROM Games
  GROUP BY HomeTeam
 UNION ALL
  SELECT AwayTeam AS team, SUM(AwayPoints) AS points
  FROM Games
  GROUP BY AwayTeam
)
GROUP BY team

请参阅SQLite文档以获取