2

我有两张桌子。球队和球员。我想做的是创建一个查询,告诉我一些关于最大团队工资的统计数据。具体来说,我想计算有多少玩家的收入低于 5K。有多少人在 5K 和 10K 之间......以 5K 的增量到最大播放器。

这是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 ,
  `Salary` INT NUll ,
  PRIMARY KEY (`ID`) );

INSERT INTO `Players` (`Name`, `Team_ID`, salary) VALUES ('Jim', '1', '4800');
INSERT INTO `Players` (`Name`, `Team_ID`, salary) VALUES ('Tom', '1', '12000');
INSERT INTO `Players` (`Name`, `Team_ID`, salary) VALUES ('Harry', '2', '1230');
INSERT INTO `Players` (`Name`, `Team_ID`, salary) VALUES ('Dave', '2', '19870');
INSERT INTO `Players` (`Name`, `Team_ID`, salary) VALUES ('Tim', '3', '1540');
INSERT INTO `Players` (`Name`, `Team_ID`, salary) VALUES ('Trey', '4','7340');
INSERT INTO `Players` (`Name`, `Team_ID`, salary) VALUES ('Jay', '4', '4800');
INSERT INTO `Players` (`Name`, `Team_ID`, salary) VALUES ('Steve', '4','6610');
INSERT INTO `Players` (`Name`, `Team_ID`, salary) VALUES ('Chris', '4','17754'); 

鉴于此数据: 道奇队是最大的球队 (ID =4) 我们希望输出:

0-5000       1
5000-10000   2
10000-15000  0
15000-20000  1

如果此代码看起来很熟悉,那是因为它是我在此处发布的先前问题的问题的演变。请不要打败我!

4

2 回答 2

3

这是我的尝试。它使用连接来满足条件:

select sr.range,
       SUM(case when p.salary >= sr.low and p.salary < sr.high then 1 else 0 end)          
from Players p join
     (select t.id
      from Players p join
           Teams t
           on p.team_id = t.id
      group by t.team_id
      order by SUM(p.salary) desc
      limit 1
     ) team
     on p.team_id = team.id cross join
     (select '0-5000' as range, 0 as low, 5000 as high union all
      select '5000-10000', 5000, 10000 union all
      select '10000-15000', 10000, 15000 union all
      select '15000-20000', 15000, 20000
     ) sr
group by sr.range
order by min(sr.low)

请注意对范围使用单独的查询,以确保您获得计数为 0 的行。

于 2013-05-21T20:39:19.230 回答
2

这段代码几乎可以完成你想要的

SELECT 5000 * FLOOR(Salary / 5000), count(*)
FROM Players 
WHERE Team_ID = 4
GROUP BY FLOOR(Salary / 5000)

它返回范围的下边界和条目数

0        1
5000     2
15000    1

请注意,它不会返回空范围。

于 2013-05-21T20:41:08.327 回答