5

私は 2 つのテーブルを持っています。1 つはチーム用で、もう 1 つはプレイヤー用です。1 つは総人数テーブルです。つまり、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
4

2 に答える 2

3

The simplest way would probably be:

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

(Although this won't include teams with no players in them.)

SQLFiddle here.

于 2013-05-21T18:05:08.143 に答える
3

First, you need the team sizes:

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;

Notice that this will return the teams with zero players too. If you don't want that, use inner join instead of left join.

Now, use this query as a row source for your final query:

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;

Hope this helps


Just one more thing.

If you have big data sets, this query may hang. So it may be best to create a temp table, index it, and run the query on the temp table:

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;
于 2013-05-21T18:05:18.627 に答える