各位神侠,请教一个 SQL 的问题。
现有一个表,名字为 table1, 表里有两列,一列是序号ID,一列是数量 NUM1(只取 0,1 两个值),比如
ID1 NUM1
1 0
2 0
3 0
4 1
5 1
6 0
7 0
8 0
9 1
...
要求在这个表上加一列 NUM2,表示NUM1中对应的序数,
对上表来说,就是
ID1 NUM1 NUM2
1 0 1
2 0 1
3 0 1
4 1 2
5 1 2
6 0 3
7 0 3
8 0 3
9 1 4
...
请问如何实现?
万分感谢!
------解决方案--------------------
数据量大不。
不大的话用个游标遍历下好了、
------解决方案--------------------
- SQL code
declare cursor my_cur is select t.rowid row_id,t.ID1,t.NUM1 from table1 t order by 1; v_count number; v_j number; v_pid number;begin v_count:=0; v_j:=1; v_pid:=0; for row_t in my_cur loop if (v_pid=row_t.NUM1) then begin update table1 set NUM2=v_j where rowid=row_t.row_id; end; else begin v_j:=v_j+1; update table1 set NUM2=v_j where rowid=row_t.row_id; v_pid:=row_t.NUM1; end; end if; v_count:=v_count+1; if (v_count>=2000) then commit; v_count:=0; end if; end loop; commit;end;/
------解决方案--------------------
cursor myCur is select * from test;
oneRow test%rowtype;
flag1 number;
flag2 number;
flag3 number;
begin
flag1:=0;
flag2:=-1;
flag3:=0;
open myCur;
fetch myCur into oneRow;
while(myCur%found)
loop
if flag2=-1 then
select num1 into flag2 from test where id=oneRow.id;
flag1:=flag1+1;
UPDATE test set num2=flag1 where id=oneRow.id;
else
select num1 into flag3 from test where id=oneRow.id;
if flag3<>flag2 then
flag1:=flag1+1;
end if;
flag2:=flag3;
UPDATE test set num2=flag1 where id=oneRow.id;
end if;
fetch myCur into oneRow;
end loop;
close myCur;
------解决方案--------------------