Question

I've made extensive research about auto-increment before posting this but couldn't find similar case:

I have a query pulling data from a main table, grouping by player_id and ordering by points desc, therefore creating a ranking output. My aim is to make the same query, once it finishes aggregating and sorting data, create a new column 'Rank' and auto increment it so it shows 1,2,3 etc since everything is already grouped by player and ordered by points DESC.

Thanks guys.

Example of the source table :

player_id-----------points-----

---1-------------------5----------

---1-------------------10---------

---1-------------------5---------

---2-------------------20---------

---2-------------------5---------

Desired output according to this example:

Rank------player_id-------score-----

----1----------2-----------25 POINTS ---------

----2----------1-----------20 POINTS ---------

EDIT

Rownum does the job well, no need for an auto increment virtual column! see Mutnowski's accepted answer below please.

Was it helpful?

Solution

Try this

SELECT @rownum:=@rownum+1 AS ‘rank’, Player_ID, Points FROM (SELECT Player_ID, SUM(Points) AS 'Points' FROM tblScores GROUP BY Player_ID ORDER BY Points DESC) AS foo, (SELECT @rownum:=0) AS foo2

I think you need to run a query to get your results without the rank, then run another query on first that selects all and adds the rank

OTHER TIPS

Applying SUM to the Points column should produce the results you want.

SELECT @rownum:=@rownum+1 AS ‘rank‘,player_id, SUM(points) 
FROM scores
GROUP BY player_id
ORDER BY SUM(points) DESC;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top