2017-10-15 73 views
0

我試圖通過人一起添加兩個組,這是我的代碼:如何添加兩個被聯合在一起的查詢

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 

(這意味着增加遊戲的國內和訪問者NUM在一起)

+0

你應該改善的問題,添加格式等 –

+0

通過格式化,你的意思是......? –

回答

1

計算機科學中的所有問題都可以通過另一個間接層面來解決。
- David Wheeler

您想同時添加相同名稱的值嗎?只要使用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; 

(UNION沒有ALL會刪除重複的,如果有相同數量的本地和訪問者遊戲可能出現這種情況)


另外,帶原始表的形式,讓他們都來一次彙總值:

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;