sql-server - 如何计算每组具有特定值的元组数?
问题描述
考虑以下架构:
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的类别
那我该怎么做呢?
解决方案
不知道为什么其他答案使用 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
,它不会起作用。
推荐阅读
- python-3.x - 我应该使用循环还是坚持使用嵌套的 if 语句?
- python - 如何使用数据框拆分新列中的两个 CSV 文件列,在熊猫中显示匹配项?
- c++ - C ++如何抛弃函数的虚拟性并调用基函数,而不是重写
- java - 块末尾的意外内容 - 是什么构建了损坏的流?
- python - 我如何获得水平小提琴图或箱线图?(在 hvplot 全息视图中默认为垂直)
- flask - sqlalchemy 结果到字典
- excel - 使用用户表单时自动滚动工作表到活动行
- powershell - 尝试在以标准用户身份运行的脚本中以管理员身份运行“reg import C:\myRegKey.reg”
- ruby - 使用 Dir.glob 不返回指定目录中的任何文件
- jquery - 如果存在很多选项卡,导航选项卡会使用省略号调整宽度