Q:

how to rank customers in sql 2008(northwind)

i have been asked to write a query which in should rank customers base on the quantity of orders they have. the main important factor is that if two customers have been ordered the  same quantity they should have be in same rank. i want to know the way to handle this query. for this i have began as below:
select tble1.customerid, RANK() OVER (ORDER BY tble1.counts desc) AS [cust grade] from
(select Orders.CustomerID, COUNT(*) as counts  from Orders 
group by CustomerID order by counts desc)tble1

as you have mentioned the output of the table should be some thing like this:
custid1--some--grade
custid2--some--grade
the problem of the code that up is that it skips some numbers. it works well, i mean if two customers have the same quantity of orders it gives them the same grade. but that seams like a queue of sequential numbers that if we have for example three 4s the next grade after them is the 7. but i need to rank it as 5. why this function works in this way. how i can fix it. if it is possible any one can suggest a better query which has a better performance i will be so much pleased.

A:

You need to use dense_rank() instead of rank() to avoid it skipping numbers.
;With tble1 AS
(
select Orders.CustomerID, 
COUNT(*) as counts  
from Orders 
group by CustomerID 
)
select tble1.customerid, 
DENSE_RANK() OVER (ORDER BY tble1.counts desc) AS [cust grade] 
from tble1

