Link to home
Start Free TrialLog in
Avatar of sopheak
sopheak

asked on

SQL update question

I have a table with 2 columns. Column1 is given and sorted ascending, what i need to do is update column2 with corresponding values.  Column 2 just should increment by one and reset to one when the value in column1 changes.



Col1      Col2
1      1
1      2
1      3
1      4
1      5
2      1
2      2
2      3
2      4
3      1
3      2
3      3
3      4
3      5
3      6
3      7
3      8
3      9
3      10


Thanks
sopheak
Avatar of Yveau
Yveau
Flag of Netherlands image

Here goes:

Hope this helps ...

-- creating original situation
create table #Y(Col1 int,Col2 int)
go
 
insert into #Y values(1, NULL)
insert into #Y values(1, NULL)
insert into #Y values(1, NULL)
insert into #Y values(1, NULL)
insert into #Y values(1, NULL)
insert into #Y values(2, NULL)
insert into #Y values(2, NULL)
insert into #Y values(2, NULL)
insert into #Y values(2, NULL)
insert into #Y values(3, NULL)
insert into #Y values(3, NULL)
insert into #Y values(3, NULL)
insert into #Y values(3, NULL)
insert into #Y values(3, NULL)
insert into #Y values(3, NULL)
insert into #Y values(3, NULL)
insert into #Y values(3, NULL)
insert into #Y values(3, NULL)
insert into #Y values(3, NULL)
go
 
-- actual code starts here
alter table #Y
add col3 int identity(1,1)
go
 
declare @c1 int
declare @c1p int
declare @c3 int
declare @c2 int
 
declare Yveau cursor
for
select col1, col3
from  #Y
 
open yveau
fetch yveau
into @c1, @c3
 
while @@fetch_status = 0
begin
        if isnull(@c1p,-1) != @c1
        begin
                set @c2 = 1
        end
        else
        begin
                set @c2 = @c2 + 1
        end
 
        update #y
        set    col2 = @c2
        where  col3 = @c3
 
        set @c1p = @c1
 
        fetch yveau
        into @c1, @c3
end
 
close yveau
deallocate yveau
 
alter table #Y
drop column col3
 
select * from #Y
 
-->> result:
Col1        Col2
----------- -----------
1           1
1           2
1           3
1           4
1           5
2           1
2           2
2           3
2           4
3           1
3           2
3           3
3           4
3           5
3           6
3           7
3           8
3           9
3           10
 
--

Open in new window

To be completely perfect, the cursor should have been declared like this:

Hope this helps ...

declare Yveau cursor
for
select col1, col3 
from #Y 
order by col3 asc
 
--

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of David Todd
David Todd
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sopheak
sopheak

ASKER

Thanks for the row_number