首页 > 解决方案 > 如何计算每组具有特定值的元组数?

问题描述

考虑以下架构:

Game(gameID, name, developID, cost, category),
Developer(developerID, name, country, speciality )

现在我想找出每个类别中美国开发商开发的游戏数量。我的尝试如下:

select category, count(developID) as TotalGames
from Game join Developer on developerID = developID
where country = 'America'
group by category;

现在这里的问题是,这个查询没有显示没有美国开发商开发过任何游戏的类别。但我希望它显示TotalGames = 0的类别

那我该怎么做呢?

标签: sql-servergroup-bycount

解决方案


不知道为什么其他答案使用 CTE,没有必要。您可以直接在连接子句中进行过滤。

您需要将连接更改为left join,并将过滤器放在on.

注意:您应该使用表别名,它们使查询更容易理解

select g.category, count(d.developerID) as TotalGames
from Game g
left join Developer d on d.developerID = g.developID and d.country = 'America'
group by g.category;

不要错误地将country过滤器放入where,它不会起作用。


推荐阅读