题目是网上看到的:
表结构如下:
create table t_money(id int primary key,amount int not null);// id 是序列号,amount是金额
对如下数据进行查询:
+----+--------+
| id | amount |
+----+--------+
| 1 | 2 |
| 2 | 2 |
| 3 | 3 |
| 4 | 5 |
| 5 | 2 |
| 6 | 8 |
| 7 | 1 |
| 8 | 2 |
| 9 | 3 |
| 10 | 3 |
+----+--------+
从表中选取若干条数据,使得被选出来的几条数据的amount(金额)字段之和等于10,要求存储过程能返回被选取出来的数据的序列号。
算法举例:2+3+5=10 返回序列号:1,3,4 ;
create table t_money(id int primary key,amount int not null);// id 是序列号,amount是金额
对如下数据进行查询:
+----+--------+
| id | amount |
+----+--------+
| 1 | 2 |
| 2 | 2 |
| 3 | 3 |
| 4 | 5 |
| 5 | 2 |
| 6 | 8 |
| 7 | 1 |
| 8 | 2 |
| 9 | 3 |
| 10 | 3 |
+----+--------+
从表中选取若干条数据,使得被选出来的几条数据的amount(金额)字段之和等于10,要求存储过程能返回被选取出来的数据的序列号。
算法举例:2+3+5=10 返回序列号:1,3,4 ;
解决存储过程为:
declare
type tabletype is table of t_test%rowtype index by binary_integer;
res tabletype;
row_1 binary_integer;
sums number;
cal varchar2(100);
seq varchar2(100);
begin
select * bulk collect into res from t_test;
for i in 1 .. 2 ** res.count loop
sums := 0;
cal := '';
seq := '';
for j in 1 .. 10 loop
if (bitand(i, 2 ** (j - 1)) <> 0) then
sums := sums + res(j).s;
cal := cal || res(j).s || '+';
seq := seq || res(j).t || ',';
if (sums > 10) then
exit;
end if;
end if;
end loop;
if (sums = 10) then
cal := substr(cal, 1, length(cal) - 1);
seq := substr(seq, 1, length(seq) - 1);
dbms_output.put_line('结果是:' || cal || '=' || sums);
dbms_output.put_line('序列是:' || seq);
exit;
end if;
end loop;
end;
以备查
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/22333206/viewspace-613311/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/22333206/viewspace-613311/