如何找到“最一致”的表演者MYSQL

时间:2013-10-16 14:44:51

标签: mysql sql

所以我有一个排行榜,我每天使用以下查询有效地获取每个用户的分数:

SELECT DATE(a.time) as time, a.userid, SUM(activity_weight) as weight

FROM activity_entries a INNER JOIN users1 u ON u.id = a.userid 

WHERE competitionId = '$competitionId' GROUP BY a.userid, DATE(time) 

ORDER BY time ASC

我想知道,在比赛的整个过程中,找到“最稳定”的表演者,即每天平均成绩最高的用户,将会是一种有效的方式。

非常感谢!

编辑:对此进行测试,但遇到问题:

SELECT a.userid,
DATE(a.time) as time,
AVG(activity_weight) AS daily_average,

(SELECT a.userid, DATE(a.time) as time,
AVG(AVG(daily_average)) as topAverage
FROM activity_entries a INNER JOIN users1 u ON u.id = a.userid
WHERE competitionId = '$competitionId'
)

FROM activity_entries a INNER JOIN users1 u ON u.id = a.userid
WHERE competitionId = '$competitionId'
GROUP BY userid, time

1 个答案:

答案 0 :(得分:2)

完全基于您提供的内容,并假设activity_weight是单个事件上特定用户的得分,然后从以下内容开始:

SELECT userid,
       time,
       AVG(activity_weight) AS daily_average
FROM activity_entries
GROUP BY userid, time

此查询返回每个用户的平均每日得分。现在,我们需要定义“最一致”。如果可接受的定义是“每日平均值的最高平均值”,则将上述查询的内部联接作为子查询,选择AVG(daily_average)

如果“最一致”需要检查标准偏差,或者比平均值更复杂的数学,那么你应该在前端程序中而不是在数据库中这样做。

编辑:尝试此查询(或在此处使用它:SQLFiddle link):

SELECT davg.userid,
   SUM(davg.daily_average*davg.num_of_activities)/SUM(davg.num_of_activities) AS weighted_total_average
FROM (
  SELECT userid,
         time,
         AVG(activity_weight) AS daily_average,
     COUNT(*) AS num_of_activities
  FROM activity_entries
  GROUP BY userid, time
) AS davg
GROUP BY davg.userid
ORDER BY AVG(davg.daily_average) DESC

数学的实际细节供您决定,但这里是一个加权平均值的例子,其中竞争者参加大量比赛的日子比懒惰的日子更有价值。