SQL SERVER TUTORIAL IN DEPTH

The blog is to help users about sql server

Others

LightBlog

Breaking

Saturday, 16 November 2013

Top n with TIES in sql server and ROW_NUM/RANK/DENSE RANK

select * from employee

id   value
23  100
24  200
25  300
26  300
27  300
28  400
29  500
30  500

select top 3 with ties from employee

 id   value
23  100
24  200
25  300
26  300
27  300


--------ROW NUMBER [JUST COUNT ]------
--------RANK[RANK ...SUPPOSE TWO ARE TIED....LETS SAY 3RD POSITION....THEN THE NEXT VALUE WILL BE 5TH POSITION.....THE TWO WHICH WERE TIED FOR 3RD..IT ASSUMES ONE WILL BE THIRD AND THE OTHER WILL BE 4TH.....SO THE NEXT NUM AFTER THIS WILL BE 5TH]
-------DENSE RANK[SUPPOSE TWO NUMBERS ARE TIED....IT ASSUMES THAT BOTH ARE TIED AT 3RD AND BOTH NEED TO SETTLE FOR THE THIRD RANK....SO THE NEXT NUMBER WILL BE 4TH]
BELOW EXAMPLE WILL CLARIFY YOU ALL THE THINGS

select custid, count(*) as numorders,
row_num() over (order by count(*) desc )  "row number"
rank() over (order by count(*) desc )  "rank"
dense_rank() over (order by count(*) desc )  "dense rank"
from orders
group by custid
order by numorders desc

custid      numorders      row number  rank    dense rank
12            39                       1                  1             1
13            37                       2                  2            2
14            26                       3                  3            3
15            25                       4                  4            4
16            25                       5                  4            4
17            25                       6                  4            4
18            20                       7                  7            5
19            18                       8                  8            6
20            18                       9                  8            7
21            17                      10                10           8
22            16                      11                11            9


--------

No comments:

Post a Comment

 test