我已经设置了以下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语句,它为任意数量的不同名称值提供最高结果。这样的事情有可能吗?
答案 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
强>