使用 LIMIT 从 MySQL 表中选择平均值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1854383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 14:41:44  来源:igfitidea点击:

Select average from MySQL table with LIMIT

sqlmysqlaverage

提问by James Simpson

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.

我试图获得价格最低的 5 个商品的平均值,按附加到它们的用户名分组。但是,下面的查询给出了每个用户的平均价格(当然是价格),但我只想返回一个答案。

SELECT AVG(price) 
  FROM table 
 WHERE price > '0' && item_id = '$id' 
GROUP BY username 
ORDER BY price ASC 
   LIMIT 5

回答by OMG Ponies

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.

它将返回 5 个最低价格的平均值 - 一个答案。

回答by Aman Dhadwal

Simple solution below.

下面简单解决。

Query:

询问:

SELECT  AVG(Column_name) 
FROM  (SELECT Column_name 
FROM  Table
WHERE  ColumnID < number[Limit you want] )