Oracle SQL:获得每个“类别”的前3个结果

时间:2018-09-26 08:19:05

标签: sql oracle greatest-n-per-group

我有一个包含多个运动队和运动项目的Oracle数据库表。 现在,我需要为每个运动项分配最低的3个团队(如果少于3个,则更少)(基于他们的ID)。

(在我的例子中,足球:巴塞罗那,皇家马德里,PSG /曲棍球:纽约岛民,纳什维尔掠食者,波士顿熊/篮球:洛杉矶湖人队,波士顿凯尔特人,克利夫兰骑士/棒球:纽约洋基)

我的表格/条目:

Create Table Teams(
teamid NUMBER,
teamname VARCHAR(20),
Sport VARCHAR(20)
);



INSERT INTO Teams (teamid, teamname, Sport) values (1, 'Barcelona', 'Soccer');
INSERT INTO Teams (teamid, teamname, Sport) values (2, 'Real Madrid', 'Soccer');
INSERT INTO Teams (teamid, teamname, Sport) values (3, 'PSG', 'Soccer');
INSERT INTO Teams (teamid, teamname, Sport) values (4, 'Liverpool', 'Soccer');
INSERT INTO Teams (teamid, teamname, Sport) values (5, 'Bayern Munich', 'Soccer');

INSERT INTO Teams (teamid, teamname, Sport) values (6, 'NY Islanders', 'Hockey');
INSERT INTO Teams (teamid, teamname, Sport) values (7, 'Nashville Predators', 'Hockey');
INSERT INTO Teams (teamid, teamname, Sport) values (8, 'Boston Bruins', 'Hockey');
INSERT INTO Teams (teamid, teamname, Sport) values (9, 'Vancouver Canucks', 'Hockey');
INSERT INTO Teams (teamid, teamname, Sport) values (10, 'NY Rangers', 'Hockey');

INSERT INTO Teams (teamid, teamname, Sport) values (11, 'LA Lakers', 'Basketball');
INSERT INTO Teams (teamid, teamname, Sport) values (12, 'Boston Celtics', 'Basketball');
INSERT INTO Teams (teamid, teamname, Sport) values (13, 'Cleveland Cavaliers', 'Basketball');
INSERT INTO Teams (teamid, teamname, Sport) values (14, 'Huston Rockets', 'Basketball');
INSERT INTO Teams (teamid, teamname, Sport) values (15, 'Chicago Bulls', 'Basketball');

INSERT INTO Teams (teamid, teamname, Sport) values (16, 'NY Yankees', 'Baseball'); 

我已经尝试过:Get top results for each group (in Oracle),但我仍然拥有所有团队。

基于示例的“我的选择语句”:

SELECT t.teamname, t.sport 
FROM teams t
  LEFT OUTER JOIN teams t2 
    ON (t.teamname = t2.teamname AND t.teamid <= t2.teamid) 
GROUP BY t.teamid, t.teamname, t.sport
HAVING COUNT(*) <= 3 
ORDER BY t.sport asc;

1 个答案:

答案 0 :(得分:2)

一个选项使用ROW_NUMBER

SELECT teamid, teamname, Sport
FROM
(
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY Sport ORDER BY teamid) rn
    FROM Teams t
) s
WHERE rn <= 3
ORDER BY Sport, teamid;