17,089
社区成员
发帖
与我相关
我的任务
分享
一个需求,可以用分析函数来解决,但是想试试通过游标来处理,其中一个已经达到目的,但是还有一个没有解决,昨天弄了半天都没解决,今天一早又起来弄,但还有有问题,来这里虚心向大神学习。
建表脚本:
create table test_20130627
(nm1 varchar2(10),
nm2 varchar2(10),
nm3 varchar2(10),
sizes varchar2(10)
;
insert into test_20130627
select '一级A','二级A','三级A','1' from dual
union all
select '一级A','二级A','三级A','2' from dual
union all
select '一级A','二级A','三级A','3' from dual
union all
select '一级A','二级A','三级A','4' from dual
union all
select '一级A','二级A','三级A','5' from dual
union all
select '一级A','二级A','三级B','1' from dual
union all
select '一级A','二级A','三级B','2' from dual
union all
select '一级A','二级A','三级B','3' from dual
union all
select '一级A','二级A','三级B','4' from dual
union all
select '一级A','二级B','三级C','1' from dual
union all
select '一级A','二级B','三级C','2' from dual
union all
select '一级A','二级B','三级C','3' from dual
union all
select '一级B','二级A','三级A','1' from dual
union all
select '一级B','二级A','三级A','2' from dual
union all
select '一级B','二级B','三级B','1' from dual
commit;
想要的结果:(就是根据nm1,nm2,nm3分组,在各组内排序)
一级A 二级A 三级Aa 1
一级A 二级A 三级Ab 2
一级A 二级A 三级Ac 3
一级A 二级A 三级Ad 4
一级A 二级A 三级Ae 5
一级A 二级A 三级Ba 1
一级A 二级A 三级Bb 2
一级A 二级A 三级Bc 3
一级A 二级A 三级Bd 4
一级A 二级B 三级Ca 1
一级A 二级B 三级Cb 2
一级A 二级B 三级Cc 3
一级B 二级A 三级Aa 1
一级B 二级A 三级Ab 2
一级B 二级B 三级Ba 1
下面是我这两天写的两个思路:
1-----------------------------------------------
/*这中方式已经达到目的,贴到这里给大家分享*/
create table temp
as
select nm1,nm2,nm3,count(1) cn from test_20130627 group by nm1,nm2,nm3;
commit;
create or replace procedure wx_20130627
is
v_n number:=1;
tmp temp%rowtype;
cursor c1 is select * from temp;
begin
open c1;
loop
fetch c1 into tmp;
v_n :=1;
exit when c1%notfound;
while v_n<=tmp.cn loop
update test_20130627 set nm3=nm3||chr(64+v_n)
where nm1=tmp.nm1
and nm2=tmp.nm2
and nm3=tmp.nm3
and sizes=v_n;
dbms_output.put_line(tmp.nm1||v_n);
v_n:=v_n+1;
end loop;
end loop;
end;
------------------------------------------------
2----------------------------------------------
/*这个语法有问题,但是不知道哪里错了,请大神看看*/
create or replace procedure wx_20130627
is
v_n number:=1;
tmp test_20130627%rowtype;
cursor c1 is select nm1,nm2,nm3 from temp;
cursor c2(p1 test_20130627%rowtype) is select * from test_20130627
where nm1=p1.nm1
and nm2=p1.nm2
and nm3=p1.nm3 for update;
begin
open c1;
loop
fetch c1 into tmp;
exit when c1%notfound;
for i in c2(tmp) loop
update test_20130627 set nm3=nm3||chr(64+v_n) where current of c2;
v_n:=v_n+1;
end loop
end loop;
close c1;
end ;
------------------------------------------------