Oracle11R2 With as的递归算法

本文介绍了在Oracle11gR2中使用WITH语句实现递归查询的方法,通过一个彩票概率问题来演示递归算法的应用。通过CTE(公共表表达式)进行递归查询,详细解释了定位点成员和递归成员的概念,并给出了示例代码。同时,提供了多个参考资料链接以深入理解递归WITH语句。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


问题来源: 

PUZZLEUP 2017
http://www.itpub.net/thread-2090903-1-1.html
(出处: ITPUB论坛-中国最专业的IT技术社区)

#1
LOTTERY

In a lottery, every week 5 different numbers are randomly drawn from numbers between 1 and 30 (including 1 and 30). What is the probability of the 3 smallest numbers drawn this week being the same with the 3 smallest numbers drawn the previous week? 

Enter your answer as a reduced fraction. 
Example: 123/4567


在彩票中,每周从1到30(包括1和30)之间的数字随机抽取5个不同的数字。本周抽到的3个最小数字与上周抽到的3个最小数字相同的概率是多少? 

答案以简化分数输入,例如:123/4567

一种解答:

SQL> with t as (select level n from dual connect by level <= 30),
  2   s as (select t1.n n1,t2.n n2,t3.n n3,t4.n n4,t5.n n5
  3          from t t1,t t2,t t3,t t4,t t5
  4          where t1.n < t2.n
  5            and t2.n < t3.n
  6            and t3.n < t4.n
  7            and t4.n < t5.n),
  8   p as (select count(*) cnt
  9          from s s1,s s2
10         where s1.n1 = s2.n1
11           and s1.n2 = s2.n2
12           and s1.n3 = s2.n3 ),
13   r as (select p1.cnt    n,
14                p2.c*p2.c m
15          from p p1,(select count(*) c from s) p2 ),
16  q(m,n) as (
17        select m,n from r
18        union all
19        select greatest(m-n,n),least(m-n,n)
20          from q
21        where m<>n)
22  select r.n/q.m||'/'||r.m/q.m as res from q,r where q.m=q.n
23  /
RES
--------------------------------------------------------------------------------
391/498771

其中 

q(m,n) as (
17        select m,n from r
18        union all
19        select greatest(m-n,n),least(m-n,n)
20          from q
21        where m<>n)
未在之前遇见过这种写法, 因此知道 oracle11g 中在with 子句中加入递归方法:

个人理解用法如下

1. 递归算法的普遍实施方式 level....contact by 参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值