我有一个带有锻炼表的 php 应用程序,我在其中存储基于事件(例如:运行、步行、骑自行车)的日常用户锻炼数据。在月底,我必须创建一个排行榜,以根据最高锻炼分数生成排名。
SELECT total_distance, user_id,date_created
FROM workouts
WHERE date_created LIKE '%2019-11%' AND activity_type='Run'.
通过上述查询,我得到如下所述的输出
我通过在查询中使用 GROUP BY user_id 优化了查询。
SELECT SUM(total_distance) as points, user_id,date_created
FROM workouts
WHERE date_created LIKE '%2019-11%' AND activity_type='Run'
GROUP BY user_id
我希望我的最终输出如第二张图片所示以及作为新列的排名。 如何为此编写查询。我做不到..
最佳答案
SELECT
CASE WHEN @l=points THEN @rank ELSE @rank:=@rank+1 END as rank,@l:=points ,points,user_id from (select
SUM(total_distance) as points, user_id,date_created
FROM workouts
WHERE date_created LIKE '%2019-07%'
GROUP BY user_id order by points desc) a, (SELECT@rank := 0) vars;
SQL 演示在这里 http://sqlfiddle.com/#!9/0e8634/2
关于php - 如何在php mysql中制作排名系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59421305/