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?
Syntax for SQL Server. The following SQL statement defines the "Personid" column to be an auto-increment primary key field in the "Persons" table: ); The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.
MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement: ALTER TABLE Persons AUTO_INCREMENT=100;
The following SQL statement defines the "Personid" column to be an auto-increment primary key field in the "Persons" table: ); The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.
By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:
You can use a CTE and row_number() to do what you want. The table @T
in the code below is only for demonstration. Replace @T
with whatever your table is called.
declare @T table ([order_id] int, [index_1] int)
insert into @T values
(600020001, 0),
(600020002, 0),
(600020002, 0),
(600020002, 0),
(600020003, 0)
;with cte as
(
select index_1,
row_number() over(partition by order_id order by (select 1)) as rn
from @T
)
update cte
set index_1 = rn
select *
from @T
Result:
order_id index_1
----------- -----------
600020001 1
600020002 1
600020002 2
600020002 3
600020003 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With