Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update column with continuous value by GROUP?

I am going to update a table with continuous value based on group.

   ItemNo       Group
  ---------------------
   null         group1      
   null         group1     
   null         group2      
   null         group2       
   null         group1      
   null         group2     
   null         group1    
   null         group2      
   null         group1      

This is an example table. I am trying to set the ItemNo field with continuous value by Group. So it will be set like this.

   ItemNo       Group
  ---------------------
   1            group1      
   2            group1     
   1            group2      
   2            group2       
   3            group1      
   3            group2     
   4            group1    
   4            group2      
   5            group1      

I tried with this query by it sets the value without considering Group.

DECLARE @id int
SET @id = 0

UPDATE table
SET @id = ItemNo = @id + 1

How can I solve this problem?

Thanks.

like image 610
tmpacifitech Avatar asked Nov 20 '25 23:11

tmpacifitech


1 Answers

;with cte as
(
select *,ROW_NUMBER() over (partition by groups order by groups) rn from YOURTABLE
)

update cte set ItemNo=rn

SQLFiddle

like image 192
Red Devil Avatar answered Nov 22 '25 15:11

Red Devil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!