如何使用子查询计算组内特定行的数量?

问题描述

架构如下:

create table Game
(
    gameID int not null,[name] varchar(30) not null,developID int,cost int not null,category varchar(30) not null,unique (gameID),primary key(gameID),);

create table Developer
(
    developerID int not null,country varchar(30) not null,speciality varchar(30) not null,unique (developerID),primary key (developerID)
);

现在,我想找出美国人为每个类别开发的游戏数量如果没有美国人在该特定类别中开发任何游戏,则必须显示 0

我将如何针对此要求编写嵌套 sql 查询。 谢谢。

解决方法

我相信这可以满足您的需求。除非您出于某种原因需要嵌套查询,否则我认为这会起作用。

select count(*),category
from Game g
join Developer d on g.developID = d.developerID
where country = 'USA'
group by category

在嵌套查询格式中,这应该可以工作,但效率低于加入版本:

select count(*)
from Game g
where developID in (select developerid from Developer where country = 'USA')