簡體   English   中英

如何在 SQL 語句中使用 GROUP BY 和 JOIN?

[英]How to use GROUP BY and JOIN in a SQL Statement?

我有兩個名為“玩家”和“國家”的表:

播放器

Person    Goals    Country
-------   -----    -------
Pogba       1      France
Pavard      1      France
Griezmann   2      France
Neymar      3      Brazil
Silva       2      Brazil

國家

Name      Continent
-------   --------------
France    Europe
Brazil    South America

我想顯示每個國家的目標總和並顯示國家名稱、大陸和總目標所以,我希望我的 output 看起來像這樣:

Country  Continent       Goals
-------  -------------   ------
France   Europe          4
Brazil   South America   5

我可以同時顯示國家和大陸以及國家和目標,但我不能同時顯示這三個。 這是我嘗試過的:

SELECT Country.Name, Country.Continent, SUM(Player.Goals)
FROM Player
INNER JOIN Country ON Player.Country = Country.Name
GROUP BY Player.Country;

也許我過度簡化了? 我只是不知道我怎樣才能得到想要的結果。

嘗試以下方法 - 也將Country.Continent添加到group by

SELECT Country.Name, Country.Continent, SUM(Player.Goals)
FROM Player
INNER JOIN Country ON Player.Country = Country.Name
GROUP BY Country.Name, Country.Continent
SELECT Country.Continent, Player.Country, SUM(Player.Goals)
FROM Player
INNER JOIN Country ON Player.Country = Country.Name
GROUP BY Country.Continent, Player.Country

嘗試這個;

SELECT Country.Name, Country.Continent, SUM(Player.Goals) as Goals
FROM Player
INNER JOIN Country ON Player.Country = Country.Name
GROUP BY Country.Name, Country.Continent;

盡管將continent添加到GROUP BY絕對是一種解決方案,但還有其他解決方案。

首先,您可以在continent上使用聚合 function :

SELECT c.Name, MAX(c.Continent) as Continent, SUM(p.Goals)
FROM Player p JOIN
     Country c
     ON p.Country = c.Name
GROUP BY c.Name;

或者,您可以使用相關子查詢:

SELECT c.*,
       (SELECT SUM(p.Goals)
        FROM Player p
        WHERE p.Country = c.Name
       ) as goals
FROM Country c;

請注意,這兩個都包括表別名,這使查詢更易於編寫和閱讀。

最后一個版本的優點是它避免了外部查詢中的聚合,並且它允許您輕松地從Country中選擇任意數量的列。 它還可以利用Player(Country)上的索引(如果可用)——盡管這與少量數據無關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM