MySQL:查找最后x条记录的每个条目的平均值

时间:2014-12-03 18:35:29

标签: mysql

我试图找出如何获得每个销售人员在过去100个评级中的平均评分,如果他们目前就业,并且他们的平均评分低于3(满分5分)。

我有以下表格(遗漏了查询中不需要的信息):

users
id    name     employed
-----------------------
1     John     1
2     Sue      1
3     Bob      0
...

sales
id     users_id
------------------
100    3
101    2
102    3
103    1
...

ratings
sales_id   rating
-----------------
100        4
101        5
102        5
103        2
...

当前查询我搜索了所有内容并返回所有订单的平均值,但我希望它只获取最近的100个评级(如果销售人员没有销售那么多项目,则更少),仍然排除任何人已不再使用或对其最近100个订单的评级大于3.这是当前查询:

SELECT u.name, avg(r.rating) as avg_rating, count(r.rating)
FROM users AS u
JOIN sales AS s ON s.users_id = u.id
JOIN ratings AS r ON r.sales_id = s.id
WHERE u.employed = 1
GROUP BY u.id
HAVING avg_rating <= 3;

任何帮助都会很棒!谢谢! :d

1 个答案:

答案 0 :(得分:2)

您可以使用我的sql变量来跟踪评分数量,这样您只能获得最近的100个评分,按sales_id排序,以便获得最近的评分。

<强> SQL FIDDLE DEMO

SELECT T.name, avg(T.rating) as avg_rating, count(T.rating)
FROM
(
  SELECT u.name, r.rating, @num := if (@name = name, @num+1, 1) as rn,
       @name:= name as var_name
  FROM users AS u
  JOIN sales AS s ON s.users_id = u.id
  JOIN ratings AS r ON r.sales_id = s.id
  AND u.employed = 1
  JOIN ( select @name :='' , @num :=1) var
  order by sales_id desc
)T
where T.rn <=100
GROUP BY T.name
HAVING avg_rating <= 3