|
//数据:id num price1 1 52 2 143 1 64 4 20//结果:id num price1 1 52 1 73 1 74 1 65 1 56 1 57 1 58 1 5//解法:with a as(select 1 id,1 num,5 price from dual union allselect 2,2,14 from dual union allselect 3,1,6 from dual union allselect 4,4,20 from dual), b as(select 1 num, rownum rnfrom (select max(num) x from a)connect by rownum <= x)select b.num, a.id, a.price / a.num price,b.rnfrom a, bwhere a.num >= b.rn/select rownum id, ta.*from(select b.num, a.price / a.num pricefrom a, bwhere a.num >= b.rn--order by a.id, b.rn) ta/这里为什么要取出max_num呢?select max(num) from aMAX(NUM)----------4//至于connect by递归查询,还有很多不明白,比如下面连个查询:SQL> select 1,rownum from dual connect by rownum<=4;1 ROWNUM---------- ----------1 11 21 31 41 5SQL> select 1,level from dual connect by level<=4;1 LEVEL---------- ----------1 11 21 31 4//select 1 num, rownum rnfrom (select max(num) x from a)connect by rownum <= xNUM RN---------- ----------1 11 21 31 41 5///这是一个获得a,b表的笛卡尔积(A×A)的查询,正如我们知道,它将返回20行select b.num, a.price / a.num pricefrom a, b//当我们加了一个条件筛选之后会是怎么样的呢?//where a.num >= b.rn这个条件限制了返回的结果集,select b.num, a.id, a.price / a.num price,b.rnfrom a, bwhere a.num >= b.rn;NUM ID PRICE RN---------- ---------- ---------- ----------1 1 5 11 2 7 11 3 6 11 4 5 11 2 7 21 4 5 21 4 5 31 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 |
|
|