Reputation: 557
Table :
a | b
1 | 15
2 | 10
3 | 20
4 | 30
Query:
SELECT AVG(table.b) FROM table ORDER BY table.a ASC LIMIT 3
Will return 18.75 instead of expected 15.
How can I change the query to get my expected result (AVG
value for a limited amount of rows)?
Upvotes: 3
Views: 1009
Reputation: 176024
You need to use subquery:
SELECT AVG(b)
FROM (SELECT b
FROM table
ORDER BY table.a ASC
LIMIT 3) sub
EDIT:
Without subquery the order of execution is like:
With subquery the order of execution is like:
More info: Logical query processing (TOP/OFFSET FETCH is the same as LIMIT).
Upvotes: 5