我有一张体操结果表,其中只记录了各个器械分数,因此我使用SUM来创建总分。显然我可以对此进行排序,但我真的想根据每个体操运动员的整体得分值为“排名/位置”添加一个额外的列,而不得不求助于PHP中的进一步处理。我也希望每个设备都有一个“等级/位置”! :)
以下是我的“结果”表中的一些示例数据:
+---------+--------------+-------+
| gymnast | apparatus_id | score |
+---------+--------------+-------+
| Isla | 1 | 12 |
| Isla | 2 | 10.4 |
| Isla | 3 | 11.5 |
| Bethany | 1 | 11.5 |
| Bethany | 2 | 10 |
| Bethany | 3 | 11 |
| Anna | 1 | 12 |
| Anna | 2 | 13 |
| Anna | 3 | 10.25 |
+---------+--------------+-------+
然后我有一个类似下面的MySQL查询,将每个设备结果合并为每个体操运动员的一个列并创建总分:
SELECT r.gymnast, app1.score AS app1_score, app2.score AS app2_score, app3.score AS app3_score, ROUND(app1.score+app2.score+app3.score, 2) AS overall_score
FROM (results r)
JOIN apparatuses a ON a.id = r.apparatus_id
LEFT JOIN results app1 ON app1.gymnast_id = r.gymnast_id AND app1.apparatus_id=1
LEFT JOIN results app2 ON app2.gymnast_id = r.gymnast_id AND app2.apparatus_id=2
LEFT JOIN results app3 ON app3.gymnast_id = r.gymnast_id AND app3.apparatus_id=3
GROUP BY r.gymnast
ORDER BY overall_score desc
所以现在我被卡住了,我怎么能在这个查询的基础上为每个设备和整体添加一个等级/位置?
+---------+------------+----------+------------+----------+------------+----------+---------------+-------------+
| gymnast | app1_score | app1_pos | app2_score | app2_pos | app3_score | app3_pos | overall_score | overall_pos |
+---------+------------+----------+------------+----------+------------+----------+---------------+-------------+
| Isla | 12 | 1 | 10.4 | 2 | 11.5 | 1 | 33.9 | 2 |
| Bethany | 11.5 | 2 | 10 | 3 | 11 | 2 | 32.5 | 3 |
| Anna | 12 | 1 | 13 | 1 | 10.25 | 3 | 35.25 | 1 |
+---------+------------+----------+------------+----------+------------+----------+---------------+-------------+
如果有人想要玩游戏,那么这里有一个SQL小提琴,其中包含一些示例数据(http://sqlfiddle.com/#!2/2e251e)。 :)
答案 0 :(得分:0)
以下查询将为您提供排名明智的gymnast_id,然后您可以加入您当前的查询
select gymnast_id,total_score, @curRank := @curRank + 1 AS rank
FROM
(select gymnast_id,sum(score) as total_score from tablename group by gymnast_id)p, (SELECT @curRank := 0) r
ORDER BY total_score desc;