Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ranking rows using SQL Server Rank function without skipping a rank number

I want to rank rows in a table without skipping numbers in the rank. Please see below example.

CREATE TABLE #test(
apples int NOT NULL,
) ON [PRIMARY]
GO

insert into #test( apples ) values ( 10 )
insert into #test( apples ) values ( 10 )
insert into #test( apples ) values ( 20 )
insert into #test( apples ) values ( 30 )

select *, RANK() over (order by apples) as theRank from #test

drop table #test
go

The result is

apples   theRank
10       1
10       1
20       3
30       4

How can I get the rank to not skip the number 2, so that the result looks like

apples   theRank
10       1
10       1
20       2<--
30       3<--

I don't have to use the Rank function, as long as I get the desired ordering.

Thanks!!

like image 984
davomarti Avatar asked Apr 05 '12 23:04

davomarti


People also ask

How do you rank rows in SQL?

The rank of a row is one plus the number of ranks that come before the row in question. 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).

What is difference between rank () ROW_NUMBER () and DENSE_RANK () in SQL?

rank and dense_rank are similar to row_number , but when there are ties, they will give the same value to the tied values. rank will keep the ranking, so the numbering may go 1, 2, 2, 4 etc, whereas dense_rank will never give any gaps.

Which is better ROW_NUMBER or rank?

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.


1 Answers

Try using DENSE_RANK instead of RANK

select *, DENSE_RANK() over (order by apples) as theRank from #test
like image 124
Abe Miessler Avatar answered Sep 21 '22 03:09

Abe Miessler