我有两张桌子。团队和球员。我想要做的是创建一个查询,告诉我一些关于最大团队薪水的统计数据。具体来说,我想要计算有多少玩家少于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
如果这段代码看起来很熟悉,那是因为它是我在这里发布的先前问题的演变。请不要打倒我!
答案 0 :(得分: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的行。
答案 1 :(得分:1)
此代码几乎可以执行您想要的操作
SELECT 5000 * FLOOR(Salary / 5000), count(*)
FROM Players
WHERE Team_ID = 4
GROUP BY FLOOR(Salary / 5000)
它返回范围的低边框和条目数
0 1
5000 2
15000 1
请注意,它不会返回空范围。