關于查詢連續3次生子小于21的問題解答
2024-07-21 02:40:24
供稿:網友
呵呵,前段時間見到一位老兄寫了個問題,最近想出了解決方案,但卻怎么
也找不到原來的發題的貼子了,找了半天,只好貼在這希望對那位老兄有點幫助
。大概我記得問題是這樣的:表名,字段名都是我瞎起的。
一個表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;
希望大家幫助指正。