我正在尝试将这两个组合在一起,这是我的代码:
SELECT VISITOR,COUNT(VISITOR)
FROM ENGLAND
WHERE TIER = 1 AND SEASON >= 1980
GROUP BY VISITOR
UNION
SELECT HOME,COUNT(HOME)
FROM ENGLAND
WHERE TIER = 1 AND SEASON >= 1980
GROUP BY HOME;
这是输出的一部分
AFC Bournemouth 37
AFC Bournemouth 38
问题是如何使输出看起来像
AFC Bournemouth 75
(这意味着将家庭和游客数量加在一起)
答案 0 :(得分:1)
计算机科学中的所有问题都可以通过另一层次的间接来解决 - 大卫惠勒
您想要将同名的值添加到一起吗?只需使用SUM()和GROUP BY:
SELECT Name, SUM(Games) AS Games
FROM (SELECT Visitor AS Name, COUNT(*) AS Games
FROM England
WHERE Tier = 1 AND Season >= 1980
GROUP BY Visitor
UNION ALL
SELECT Home, COUNT(*)
FROM England
WHERE Tier = 1 AND Season >= 1980
GROUP BY Home)
GROUP BY Name;
(没有ALL的UNION会删除重复项,如果有相同数量的主场和访客游戏,可能会发生重复。)
或者,将原始表格的值以允许所有内容全部聚合的形式显示:
SELECT Name, COUNT(*) AS Games
FROM (SELECT Visitor AS Name
FROM England
WHERE Tier >= 1 AND Season >= 1980
UNION ALL
SELECT Home
FROM England
WHERE Tier >= 1 AND Season >= 1980)
GROUP BY Name;