SQL Server Dense Rank in reverse order

4.7k views Asked by At

I have 3 columns, they are created by Dense Rank, Count, and Row Number

DR C RN
1   4   1
2   4   2
3   4   3
4   4   4

Is there any way for the DENSE_RANK or some other ranking function return in reverse order?

Like this

DR C RN
4   4   1
3   4   2
2   4   3
1   4   4

Thanks,

2

There are 2 answers

1
Pரதீப் On

try this. Use order by RN desc in dense rank over clause

SELECT Dense_rank () OVER (partition BY c ORDER BY rn DESC) DN,
       *
FROM  (SELECT 4 C,1 RN
       UNION ALL
       SELECT 4,2
       UNION ALL
       SELECT 4,3
       UNION ALL
       SELECT 4,4) A
ORDER  BY dn DESC 

OUTPUT :

DN  C   RN
--  --  --
4   4   1
3   4   2
2   4   3
1   4   4
1
Alireza Balavand On

you should use DESC in dense_rank

    DENSE_RANK() OVER (PARTITION BY t.t1 ORDER BY (t.t2) DESC) DENSE_RANK