简体   繁体   中英

How to count number of specific rows within a group by using a subquery?

The schema is as follows:

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,
    [name] varchar(30) not null,
    country varchar(30) not null,
    speciality varchar(30) not null,
    unique (developerID),
    primary key (developerID)
);

Now, I want to find out the number of games developed by an American for each category. It must show 0 if no American has developed any game in that specific category

How would I write a nested SQL query for this requirement. Thanks.

I believe this gets what you need. Unless there's some reason you need a nested query, this will work I think.

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

In nested query format, this should work, but it's less efficient than the joined version:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM