Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to calculate rank with group by in sql?

Suppose if I have table1 as following

Category  Brand  Value     
A           A1     4
B           B1     7
C           C1     8
A           A2     3
B           B2     4
C           C2     6
A           A3     9
B           B3     10
C           C3     1
A           A4     5

Now if I want to calculate rank for each brand but grouped by category how do I go about it?

Something like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Select rank() (over value)
from table
group by category 

Expected output is this:

Category      Brand Value     Rank
A               A3    9         1
A               A4    5         2
A               A1    4         3
A               A2    3         4
B               B3    10        1
B               B1    7         2
B               B2    4         3
C               C1    8         1
C               C2    6         2
C               C3    1         3

>Solution :

Maybe you are looking for something like this.
See this official documentation on DENSE_RANK for more details

select brand, category, dense_rank() over(partition by category order by value desc) as dr
from table
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading