//数据: id num price 1 1 5 2 2 14 3 1 6 4 4 20 //结果: id num price 1 1 5 2 1 7 3 1 7 4 1 6 5 1 5 6 1 5 7 1 5 8 1 5 //解法: with a as( select 1 id,1 num,5 price from dual union all select 2,2,14 from dual union all select 3,1,6 from dual union all select 4,4,20 from dual) , b as( select 1 num, rownum rn from (select max(num) x from a) connect by rownum <= x) select b.num, a.id, a.price / a.num price,b.rn from a, b where a.num >= b.rn / select rownum id, ta.* from( select b.num, a.price / a.num price from a, b where a.num >= b.rn-- order by a.id, b.rn) ta /这里为什么要取出max_num呢? select max(num) from a MAX(NUM) ---------- 4 //至于connect by递归查询,还有很多不明白,比如下面连个查询: SQL> select 1,rownum from dual connect by rownum<=4; 1 ROWNUM ---------- ---------- 1 1 1 2 1 3 1 4 1 5 SQL> select 1,level from dual connect by level<=4; 1 LEVEL ---------- ---------- 1 1 1 2 1 3 1 4 // select 1 num, rownum rn from (select max(num) x from a) connect by rownum <= x NUM RN ---------- ---------- 1 1 1 2 1 3 1 4 1 5 / //这是一个获得a,b表的笛卡尔积(A×A)的查询,正如我们知道,它将返回20行 select b.num, a.price / a.num price from a, b //当我们加了一个条件筛选之后会是怎么样的呢? //where a.num >= b.rn这个条件限制了返回的结果集, select b.num, a.id, a.price / a.num price,b.rn from a, b where a.num >= b.rn; NUM ID PRICE RN ---------- ---------- ---------- ---------- 1 1 5 1 1 2 7 1 1 3 6 1 1 4 5 1 1 2 7 2 1 4 5 2 1 4 5 3 1 4 5 4 //从结果集中,我们看出,a表将所以的记录与b表中的每一条记录一遍一遍的比较; //对于b表中第一条数据,a表中所有的行的num都大于它,所以这里返回了rn=1对应的4条记录; //b表中rn=2,a表中只有id=2,4的数据的num大于它,所以price只返回7,5; //b表中rn=3,a表中只有id=4的这条数据的num大于它,所以price返回5; //b表中rn=4,a表中只有id=4的这条数据的num与之对应,所以price=5 //上面的结果就是这么来的; // 原帖:http://topic.csdn.net/u/20110607/00/60fef66a-d97a-4d1b-9642-594b77370559.html