关于查询连续3次生子小于21的问题解答


呵呵,前段时间见到一位老兄写了个问题,最近想出了解决方案,但却怎么

也找不到原来的发题的贴子了,找了半天,只好贴在这希望对那位老兄有点帮助

。大概我记得问题是这样的:表名,字段名都是我瞎起的。
一个表pigs,里面有字段生产匹次:numbers,猪号:pig_id,生产批次:

pigbirthday,生产数量:pigsonnum;选出所有连续3次生子数量小于21的猪。
number pig_id pigbirthday pigsonnum
1 11 15 20
2 22 16 22
3 11 17 19
4 33 18 21
5 11 19 18
大概是这个样子的我的过程如下:
1:创建表rightpig用于存放选出连续3次生子数量小于21的猪;
create table rightpig(pig_id char(6));
2:创建选猪存储过程。
create or replace procedure findpig
is
sums number; --临时存储连续生产小于21天的次数。
pigsonmums number;--临时存储生产猪的个数。
cursor findallpig is select distinct pig_id from pigs; -- 从表里选出

--所有猪。
cursor findrightpig(pig_ids char(6)) is select pigsonnum from pigs

where pig_id=pig_ids order by pigbirthday; --从表里选出一头猪的各批次

--生子数量并以批次排序。
begin
open cursor findallpig;
fetch findallpig into pigids; --从表里逐一选出猪的id号并存入变量

pigids;
loop
open cursor findrightpig(pigids); --将猪的id号代入游标,按出生批次先后

--选出猪的各批次生子数量并放入变量pigsonnums。
fetch findrightpig into pigsonnums;
sums=0;
loop
if pigsonnums<21 then --如果生子数量小于21则累计批次加一;
sums=sums+1;
if sums>3 then --如果连续3次则将此猪插入表rightpig,并退出这只

--猪的循环;
insert into rightpig
values('pigids');
exit loops;
end if;
else sums=0; --如果生子数量大于21则将累计批次置零,并继续查询。
end if;
end loop;
close cursor findrightpig;
end loop;
end cursor findallpig;
end;
希望大家帮助指正。

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus