这是我的架构:
create TABLE sample (
userId INT,
score INT
);
INSERT INTO sample VALUES (1,10);
INSERT INTO sample VALUES (1,15);
INSERT INTO sample VALUES (1,20);
INSERT INTO sample VALUES (2,100);
INSERT INTO sample VALUES (2,200);
INSERT INTO sample VALUES (2,500);
INSERT INTO sample VALUES (4,100);
INSERT INTO sample VALUES (4,200);
INSERT INTO sample VALUES (4,500);
INSERT INTO sample VALUES (3,5);
INSERT INTO sample VALUES (3,5);
INSERT INTO sample VALUES (3,10);
INSERT INTO sample VALUES (3,7);
INSERT INTO sample VALUES (3,2);
我想找到平均得分最高的用户ID。注意可能有不止一个!所以对于上面的样本数据,答案是:2和4,因为它们的平均得分为266.666 ....
我有一个解决这个问题的SQL:
select s.USERID
from sample s
group by USERID
having AVG(s.SCORE) IN (
-- Gets the Maximum Average Score (returns only 1 result)
select MAX(average_score) as Max_Average_Score
from (
-- Gets the Average Score
select AVG(s2.SCORE) as average_score
from sample s2
group by USERID
)
);
但我觉得这有点低效,因为我计算两次平均分数。一次用于主SQL,再次用于查找最大平均得分。还有更好的方法吗?
注意:我正在使用SQL Plus
答案 0 :(得分:4)
select userid from
(select userid, rank() over (order by avg(score) desc) rw
from sample group by userid)
where rw = 1;
计算每个用户的平均分数,然后使用分析函数(在分组后执行)计算每个分数的等级。最后得到排名第一的行
答案 1 :(得分:2)
我只能说我将如何使用DB2 SQL解决这个问题 我会创建一个临时表,您可以在其中保存每个用户的平均分数,并从中选择最大值。这在sql plus中也是可能的:How to create a temporary table in Oracle。
以下是DB2语法(未测试)
中的解决方案http://www.cs.newpaltz.edu/~pletcha/DB/db2_TempTables.html
WITH tempTable
AS (select userid, AVG(score) FROM sample GROUP BY userid)
SELECT * FROM tempTable WHERE score = (SELECT MAX(score) FROM tempTable)
答案 2 :(得分:0)
Listo,改为Oracle:
select userId, AVG(score) AS promedio
from [sample]
where rownum = 1
group by userId
order by AVG(score) desc