如何计算每组具有特定值的元组数?

时间:2021-04-19 13:18:39

标签: sql-server group-by count

考虑以下架构:

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

的类别

那我该怎么做?

1 个答案:

答案 0 :(得分:1)

不确定为什么其他答案使用 CTE,没有必要。可以直接在join子句中过滤。

您需要将连接更改为 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 中,它不会起作用。