获取一组记录的平均值

时间:2013-12-16 09:16:14

标签: mysql average

我有一个有关类别(价格,视图,设施,位置)的露营地的评论表。 以下查询用于按平均四个类别显示前20个评论。

SELECT
  ROUND(((R.price + R.location + R.facilities + R.view) / 4), 2) AS avg,
  R.poi_id,
  poi.Name
FROM
  `Reviews` AS `R`
  LEFT JOIN `poi` ON `R`.`poi_id` = `poi`.`ID`
ORDER BY avg DESC
LIMIT 20

但是我已经意识到查询不适合同一个露营地有多个评论的情况。

那么有一个查询会返回最高的20个评级露营地(poi),其中包含该poiID的平均价格,视图,设施,位置/评论数量?

1 个答案:

答案 0 :(得分:0)

平均功能当然是累积的,但你可以通过SUM评论分数和COUNT他们的数字来实现它:

SELECT
  ROUND(((R.price + R.location + R.facilities + R.view) / 4 * cnt), 2) AS avg,
  R.poi_id,
  poi.Name
FROM
  (SELECT SUM(price) AS price, 
          SUM(location) AS location,
          SUM(facilities) AS facilities,
          SUM(view) AS view,
          COUNT(*) AS cnt,
          poi_id
   FROM   Review
   GROUP BY poi_id) AS `R`
  LEFT JOIN `poi` ON `R`.`poi_id` = `poi`.`ID`
ORDER BY avg DESC
LIMIT 20