获取每个唯一ID

时间:2018-01-05 09:55:14

标签: sum

enter image description here这是我目前正在使用的查询

SELECT SUM(score) as score FROM (SELECT p2.score FROM performance_buzz as p2 WHERE p2.player_id = 922 ORDER BY p2.id DESC LIMIT 5) as performance_buzz

但是在上面的查询中我需要手动传递player_id,我不想这样做。我想用mysql的方式做这个,因为我想使用这个查询作为子查询来获得每个玩家的最后5行得分总和

SELECT performance_buzz.id, performance_buzz.score as last_score, performance_buzz.name

FROM `performance_buzz` 

LEFT JOIN performance_buzz m2 ON (performance_buzz.name = m2.name AND performance_buzz.id < m2.id)  

WHERE m2.id IS NULL 

GROUP BY performance_buzz.name 

ORDER BY performance_buzz.id DESC

1 个答案:

答案 0 :(得分:0)

应该是这样的:

select player_id, sum(score) score
from
(
    SELECT 
        @row_number:=CASE
            WHEN @player_id = player_id THEN @row_number + 1
            ELSE 1
        END AS rn,
        @player_id:=player_id as player_id,
        score
    FROM
        performance_buzz,(SELECT @player_id:=0,@row_number:=0) as t
   order by player_id, id desc
) a
where rn <= 5
group by player_id