26

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
OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
James Simpson
  • 13,488
  • 26
  • 83
  • 108
  • 1
    I don't understand what you're trying to do. Can you give an example table structure, some example data and the expected result for that data? – Mark Byers Dec 06 '09 at 04:45

2 Answers2

62

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.

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
0

Simple solution below.

Query:

SELECT  AVG(Column_name) 
FROM  (SELECT Column_name 
FROM  Table
WHERE  ColumnID < number[Limit you want] ) alias
John
  • 7,507
  • 3
  • 52
  • 52