Here is my schema:
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);
I want to find the user ID's of those who have the maximum highest average score. Note there could be more than one! So for the above sample data, the answer would be: 2 and 4, becuase they both have a average score of 266.666... .
I have a working SQL for this problem:
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
)
);
But I think it is a bit inefficient because I'm calculating the average score twice. Once for the main SQL and again for finding the max avg score. Is there a better way?
Note: I'm using SQL Plus