简体   繁体   中英

Update SQL with consecutive numbering within a group

I found the technique to update rows of a table with consecutive numbers here:

Update SQL with consecutive numbering

The gist of the technique is to use (T-SQL):

update myTable
SET @myvar = myField = @myVar + 1

which is awesome and works very well.

Can this technique be extended to number different groups of records, with each group starting with 1 ? eg

  • Category 1 rows should get a sequence number 1,2,3,....
  • Category 2 rows should also get a sequence number 1,2,3,.....

You can simply add a WHERE Clause to your UPDATE statement. see http://dev.mysql.com/doc/refman/5.0/en/update.html for reference.

Basically you do something like:

update myTable
SET @myvar = myField = @myVar + 1
WHERE myCategory = 'CAT'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM