Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Query for Rank (RowNumber) and Groupings

Tags:

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.

like image 284
bladefist Avatar asked Jul 16 '09 19:07

bladefist


People also ask

How can use RANK and row number function in SQL?

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.

What is difference between RANK () ROW_NUMBER () and Dense_rank () in SQL?

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.

What is ROW_NUMBER () and partition by in SQL Server?

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.


1 Answers

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 
like image 163
gbn Avatar answered Sep 19 '22 20:09

gbn