user1542125
user1542125

Reputation: 615

sql avg not returning expected result

I'm running the following on my sqlite3 DB, but the result is not limited to the last 3 records. It is returning the average for all records.

SELECT AVG(time) FROM tbl_aa ORDER BY ID LIMIT 3

Any thoughts?

Upvotes: 0

Views: 42

Answers (2)

Chris L
Chris L

Reputation: 2292

Limit will restrict the number of results in your result set, however AVG is calculated on the entire set so will only return one row. Therefore the limit is redundant.

Upvotes: 1

juergen d
juergen d

Reputation: 204746

Use a subquery to get the first 3 records and then calculate the average on them

select avg(time) from
(
   SELECT time
   FROM tbl_a 
   ORDER BY ID 
   LIMIT 3
) x

Upvotes: 3

Related Questions