Oracle 10中的嵌套cos()计算

时间:2013-04-22 12:05:58

标签: oracle oracle10g recursive-query

我有一些带有一些正整数的表

n
----
1
2
5
10

对于此表的每一行,我希望值cos(cos(...cos(0)..))cos被应用n次)通过SQL语句计算 (PL / SQL存储过程和函数是不允许的):

n   coscos
--- --------
1   1
2   0.540302305868
5   0.793480358743
10  0.731404042423

can使用递归查询在Oracle 11g中执行此操作 是否可以在Oracle 10g中执行相同的操作?

2 个答案:

答案 0 :(得分:1)

MODEL子句可以解决这个问题:

测试数据:

create table test1(n number unique);
insert into test1 select * from table(sys.odcinumberlist(1,2,5,10));
commit;

<强>查询:

--The last row for each N has the final coscos value.
select n, coscos
from
(
    --Set each value to the cos() of the previous value.
    select * from
    (
        --Each value of N has N rows, with value rownumber from 1 to N.
        select n, rownumber
        from
        (
            --Maximum number of rows needed (the largest number in the table)
            select level rownumber
            from dual
            connect by level <= (select max(n) from test1)
        ) max_rows
        cross join test1
        where max_rows.rownumber <= test1.n
        order by n, rownumber
    ) n_to_rows
    model
    partition by (n)
    dimension by (rownumber)
    measures (0 as coscos)
    (
        coscos[1] = cos(0),
        coscos[rownumber > 1] = cos(coscos[cv(rownumber)-1])
    )
)
where n = rownumber
order by n;

结果:

N   COSCOS
1   1
2   0.54030230586814
5   0.793480358742566
10  0.73140404242251

让圣战开始:

这个查询是个好主意吗?我不会在生产中运行此查询,但希望它是一个有用的演示,可以用SQL解决任何问题。

我已经看到浪费了数千小时,因为人们害怕使用SQL。如果您大量使用数据库,那么不使用SQL作为主要编程语言是很愚蠢的。偶尔花几个小时测试SQL的限制是件好事。一些奇怪的查询是一个很小的代价,以避免感染许多数据库程序员的灾难性的逐行处理思维。

答案 1 :(得分:1)

使用WITH FUNCTION(Oracle 12c):

WITH FUNCTION coscos(n INT) RETURN NUMBER IS
BEGIN
   IF n > 1 
     THEN RETURN cos(coscos(n-1));
     ELSE RETURN cos(0);   
   END IF;
END;
SELECT n, coscos(n)
FROM t;

db<>fiddle demo

输出:

+-----+-------------------------------------------+
| N   |                 COSCOS(N)                 |
+-----+-------------------------------------------+
|  1  |                                         1 |
|  2  | .5403023058681397174009366074429766037354 |
|  5  |  .793480358742565591826054230990284002387 |
| 10  | .7314040424225098582924268769524825209688 |
+-----+-------------------------------------------+