SQL Server 2005
I have a table containing the following: –
[order_id] [index_1]
600020001 0
600020002 0
600020002 0
600020002 0
600020003 0
...
which needs to be updated to: –
[order_id] [index_1]
600020001 1
600020002 1
600020002 2
600020002 3
600020003 1
I am trying to write an UPDATE statement that will populate the index_1 field, as per the example above. I can acheive this using a CURSOR, but ideally would like to do it without if possible.
For each new order_id the numbering restarts. For each order_id row the index_1 field is incremented by 1.
Is it possible to do this without a cursor?
You can use a CTE and row_number() to do what you want. The table
@Tin the code below is only for demonstration. Replace@Twith whatever your table is called.Result: