So, I have the following table where
Col1 can have 2 values: A or B
Col2 can have 2 values: P or Q
Col3 can have 3 values: L, M or N
Roll_number is just a numeric Id number
Roll_number , Col1 , Col2, Col3
121212 , A , P, L
131313 , A , P, L
141414 , B , P, M
525252 , A , Q, L
626262 , B , P, M
929292 , A , Q, L
939393 , A , P, N
232323 , B , Q, L
090909 , B , P, L
303030 , B , Q, N
505050 , A , Q, M
608960 , A , Q, L
What I would like to have is the following after "grouping" by on Col1, Col2 and Col3:
Roll_number , Col1 , Col2, Col3, Group_Name
121212 , A , P, L, 1
131313 , A , P, L, 1
141414 , B , P, M, 2
626262 , B , P, M, 2
525252 , A , Q, L, 3
929292 , A , Q, L, 3
608960 , A , Q, L, 3
939393 , A , P, N, 4
232323 , B , Q, L, 5
090909 , B , P, L, 6
303030 , B , Q, N, 7
505050 , A , Q, M, 8
How do I achieve this?
2
Answers
I believe you can use dense_rank () function in MYSQL.
The ORDER BY clause can be adjusted as per your need. Dense_Rank() is a window function that ranks rows in partitions with no gaps in the ranking values.
It is not quite clear what are the rules for group numbers assignment. One of the ways to give you the exact expected result with the sample data provided could be like this:
… had to use some hardcodings to assigne groups 1, 2 and 3 …