Skip to content
Advertisement

Renumbering A Column Based On Other Columns

This table contains Purchase Orders which can have multiple lines per order. Right now the table appears like this.

Purchase_OrderNumber Account_Number Line_Number
174558 0000448 1
174558 0000448 2
175812 295812 1
175812 295812 1
175812 295812 2
175812 295812 545
175812 295812 26686
175812 295812 53481
175813 295812 1
175813 295812 2
175813 295812 5

What I need is some SQL statement that will re-number the Line_Number column to based on the Purchase_OrderNumber and Account_Number Columns. So the end result should look like this:

Purchase_OrderNumber Account_Number Line_Number
174558 0000448 1
174558 0000448 2
175812 295812 1
175812 295812 2
175812 295812 3
175812 295812 4
175812 295812 5
175812 295812 6
175813 295812 1
175813 295812 2
175813 295812 3

I do not have much experience with SQL. I could write a Select query to extract the data, write some C# logic to renumber it, and then update the table. However, I would like to see if it could be simplified by handling it all in an SQL statement.

Advertisement

Answer

Use row_number():

EDIT:

If you are using SQL Server, you can just use an updatable CTE:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement