I have a table that has some columns: User, Category, Value
And I want to make a query that will give me a ranking, of all the users by the value, but reset for the category.
Example:
user1 CategoryA 10 user2 CategoryA 11 user3 CategoryA 9 user4 CategoryB 3 user1 CategoryB 11
the query would return:
Rank User Category 1 user2 CategoryA 2 user1 CategoryA 3 user3 CategoryA 1 user1 CategoryB 2 user4 CategoryB
Any ideas?
I write the query and specify the Category, It works but then I have to write loops and its very slow.
ROW_NUMBER and RANK are similar. ROW_NUMBER numbers all rows sequentially (for example 1, 2, 3, 4, 5). RANK provides the same numeric value for ties (for example 1, 2, 2, 4, 5). ROW_NUMBER is a temporary value calculated when the query is run.
The row_number gives continuous numbers, while rank and dense_rank give the same rank for duplicates, but the next number in rank is as per continuous order so you will see a jump but in dense_rank doesn't have any gap in rankings.
PARTITION BYIt is an optional clause in the ROW_NUMBER function. It is a clause that divides the result set into partitions (groups of rows). The ROW_NUMBER() method is then applied to each partition, which assigns a separate rank number to each partition.
Use "Partition by" in the ranking function OVER clause
SELECT Rank() over (Partition by Category Order by Value, User, Category) as ranks, Category, User FROM Table1 Group By User, Category, Value Order by ranks asc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With