【问题标题】:How to count number of specific rows within a group by using a subquery?如何使用子查询计算组内特定行的数量?
【发布时间】:2021-07-23 00:30:38
【问题描述】:

架构如下:

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)
);

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

我将如何为此要求编写嵌套 SQL 查询。 谢谢。

【问题讨论】:

  • Game.developID = Developer.developerID 吗?
  • @jw11432 是的。

标签: sql-server group-by count nested-query


【解决方案1】:

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

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')

【讨论】:

  • 但我希望用嵌套查询来完成
猜你喜欢
  • 2011-08-17
  • 2011-07-22
  • 2011-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-14
  • 2011-02-27
  • 1970-01-01
相关资源
最近更新 更多