user123
user123

Reputation: 425

SQL Server / incremental column per grouping

I just have one question in SQL server.

I have table table1 containing the below rows.

col1  col2
----------
A      X
A      X
A      Y
A      Y
A      Z
B      X
B      Z
B      Z
C      V

I want to add a new column col3 to the table as incremental of grouping of col1 and col2 , as shown below :

col1  col2  col3
-----------------
A      X      1
A      X      1
A      Y      2
A      Y      2
A      Z      3
B      X      1
B      Z      2
B      Z      2
C      V      1

Upvotes: 0

Views: 28

Answers (1)

Siyual
Siyual

Reputation: 16917

You can do this with a DENSE_RANK():

Select  col1, col2, 
        Dense_Rank() Over (Partition By col1 Order By col2) As Col3
From    Table1

Upvotes: 3

Related Questions