获得"高分"从得分表的表

时间:2016-04-13 21:47:55

标签: sql oracle

我已经设置了以下sql表设置来跟踪不同玩家的得分。

create table scoreTable (
  userName varchar2(100),
  score number
)
/
insert into scoreTable values ('Andy', 200);
insert into scoreTable values ('Andy', 33);
insert into scoreTable values ('Bob', 444);
insert into scoreTable values ('Charlie', 213);
insert into scoreTable values ('Charlie', 4);
insert into scoreTable values ('Charlie', 777);

现在我想使用select语句返回每位玩家的最高分。我希望结果是

NAME      SCORE
_____     ____
Andy      200
Bob       444
Charlie   777

我更喜欢只有一个select语句,它为任意数量的不同名称值提供最高结果。这样的事情有可能吗?

1 个答案:

答案 0 :(得分:1)

  

这样的事情可能吗?

简单汇总:

SELECT userName, MAX(score) AS score
FROM scoreTable
GROUP BY userName
ORDER BY userName;

LiveDemo

修改

使用RANK函数返回整行:

WITH cte AS
(
     SELECT *, RANK() OVER(PARTITION BY userName ORDER BY score DESC) AS rn
     FROM scoreTable
)
SELECT *
FROM cte
WHERE rn = 1
ORDER BY userName;

或使用SELF JOIN

SELECT s1.*
FROM scoreTable s1
LEFT JOIN scoreTable s2
  ON s1.userName = s2.userName
 AND s1.score < s2.score
WHERE s2.userName IS NULL
ORDER BY userName;

LiveDemo