![](/img/trans.png)
[英]How to return SUM of Column and COUNT of rows with GROUP BY in SQL Server
[英]Count/sum rows and group them by another column
我從 SQL 開始,我在分組 2 列時遇到問題。 我需要由另一列過濾計數,但我獲得所有行的計數,就好像它們沒有被分組一樣。
我有 4 張不同的桌子,上面有國家、城市、比賽和體育場。 我必須獲得國家和城市的名稱和代碼,以及在每個城市工作的裁判人數以及每個城市的總進球數。 我已經這樣做了,但我獲得了在比賽中工作的裁判總數和比賽期間的總進球數:
SELECT ci.city_code,
ci.city_name,
co.country_code,
co.country_name,
COUNT(DISTINCT referee_code),
SUM(home_goals+visitor_goals)
FROM euro2021.tb_city AS ci
INNER JOIN euro2021.tb_country AS co ON ci.country_code=co.country_code
INNER JOIN euro2021.tb_match AS m ON ci.city_name=ci.city_name
INNER JOIN euro2021.tb_stadium AS st on st.stadium_code=m.stadium_code
GROUP BY ci.city_code, ci.city_name, co.country_code, co.country_name
你有什么想法或者你知道這是否以前回答過? 提前致謝。
我認為問題全部出在您的 JOIN 子句中。 我相信你想要這個:
SELECT ci.city_code,
ci.city_name,
co.country_code,
co.country_name,
COUNT(DISTINCT m.referee_code),
SUM(m.home_goals+m.visitor_goals)
FROM euri2021.tb_match AS m
INNER JOIN euro2021.tb_stadium AS st ON st.stadium_code=m.stadium_code
INNER JOIN euro2021.tb_city AS ci ON ci.city_code=st.city_code
INNER JOIN euro2021.tb_country AS co ON ci.country_code=co.country_code
IROUP BY ci.city_code, ci.city_name, co.country_code, co.country_name;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.