Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select average from MySQL table with LIMIT

Tags:

sql

mysql

average

I am trying to get the average of the lowest 5 priced items, grouped by the username attached to them. However, the below query gives the average price for each user (which of course is the price), but I just want one answer returned.

SELECT AVG(price)    FROM table   WHERE price > '0' && item_id = '$id'  GROUP BY username  ORDER BY price ASC     LIMIT 5 
like image 380
James Simpson Avatar asked Dec 06 '09 04:12

James Simpson


People also ask

How do I SELECT AVG in MySQL?

You use the DISTINCT operator in the AVG function to calculate the average value of the distinct values. For example, if you have a set of values 1,1,2,3, the AVG function with DISTINCT operator will return 2 i.e., (1 + 2 + 3) / 3 .

How do you find the average mark on a student table?

In SQL, sometimes we need to find the average value of a column based on another column of the table such as finding the student-wise average marks scored by him/her in all the subjects. This involves the use of the GROUP BY clause along with the AGGREGATE function like AVG.

Can we use limit with GROUP BY in SQL?

No, you can't LIMIT subqueries arbitrarily (you can do it to a limited extent in newer MySQLs, but not for 5 results per group). This is a groupwise-maximum type query, which is not trivial to do in SQL.

How do I find the average of each row in SQL?

The average is simply calculated by summing the amounts and divide by the difference between min and max dates for each row.


1 Answers

I think this is what you're after:

SELECT AVG(items.price)   FROM (SELECT t.price           FROM TABLE t          WHERE t.price > '0'             AND t.item_id = '$id'       ORDER BY t.price          LIMIT 5) items 

It will return the average of the 5 lowest prices - a single answer.

like image 91
OMG Ponies Avatar answered Oct 05 '22 23:10

OMG Ponies