9

Is it possible to SUM or AVG the top 10 results? I have a list of several thousand values. I want to know the average of the top 10 values. I tried this:

SELECT AVG(some_val)
FROM table
ORDER BY some_val DESC
LIMIT 10;

But this gives me the average of the entire list of values from the table, not just the top 10.

I'm using MySQL. I'd like to write this as one SQL statement.

1 Answer 1

9

You need to select the top 10 rows first, then average them.

SELECT AVG(some_val)
  FROM (SELECT * FROM table ORDER BY some_val DESC LIMIT 10) t;

Otherwise, you are selecting the average of all the rows, and then returning up to 10 results (because LIMIT applies last). As you probably discovered, you only get a single row back (the average), and the LIMIT has no effect.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.