在mySql中计算不同的计数

时间:2013-05-21 17:59:58

标签: mysql count distinct

我有两个表一个用于团队一个用于玩家我想要找出的是总人数表,换句话说我想要计算有2个成员的团队总数,对所有人来说拥有3名成员等的团队数量

这是数据库结构。

(补充工具栏问题:我是新手:有没有更好的方式发布SQL?)

CREATE  TABLE `formsfiles`.`Teams` (
  `ID` INT NOT NULL AUTO_INCREMENT ,
  `Name` VARCHAR(45) NULL ,
  PRIMARY KEY (`ID`) );


INSERT INTO `Teams` (`Name`) VALUES ('Sharks');
INSERT INTO `Teams` (`Name`) VALUES ('Jets');
INSERT INTO `Teams` (`Name`) VALUES ('Fish');
INSERT INTO `Teams` (`Name`) VALUES ('Dodgers');


CREATE  TABLE `Players` (
  `ID` INT NOT NULL AUTO_INCREMENT ,
  `Name` VARCHAR(45) NULL ,
  `Team_ID` INT NULL ,
  PRIMARY KEY (`ID`) );

INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Jim', '1');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Tom', '1');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Harry', '2');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Dave', '2');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Tim', '3');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Trey', '4');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Jay', '4');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Steve', '4');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Chris', '4');

我想要的是计算团队规模。

我想看到以下输出

Team_Size  Count
1          1
2          2
4          1

2 个答案:

答案 0 :(得分:3)

最简单的方法可能是:

select team_count, count(*) from
(select count(*) team_count from players group by team_id) sq
group by team_count

(虽然这不包括没有球员的球队。)

SQLFiddle here

答案 1 :(得分:3)

首先,您需要团队规模:

select t.id as teamId, count(p.id) as teamSize
from 
    `Teams` as t
    left join `Players` as p on t.id = p.teamId
group by
    t.id;

请注意,这将使球队的球员归零。如果您不想这样做,请使用inner join代替left join

现在,将此查询用作最终查询的行来源:

select teamSize, count(teamId)
from (
    select t.id as teamId, count(p.id) as teamSize
    from 
        `Teams` as t
        left join `Players` as p on t.id = p.teamId
    group by
        t.id) as a
group by teamSize;

希望这有帮助


还有一件事。

如果您有大数据集,此查询可能会挂起。因此,最好创建临时表,对其进行索引,然后在临时表上运行查询:

drop table if exists temp_teamSize;
create temporary table temp_teamSize
    select t.id as teamId, count(p.id) as teamSize
    from 
        `Teams` as t
        left join `Players` as p on t.id = p.teamId
    group by
        t.id;
alter table temp_teamSize
    add unique index idx_teamId(teamId),
    add index idx_teamSize(teamSize);
select teamSize, count(teamId)
from temp_teamSize
group by teamSize;