2011-11-18 227 views
1

查找階乘我有有一欄呼叫號碼在甲骨文

Numbers 
------ 
3 
5 

我試圖讓那些階乘的表。我使用下面的邏輯,但不正確的結果

Select 
    Numbers 
    ,EXP(SUM(LN(Numbers)) OVER (ORDER BY Numbers)) Factorial 
FROM testTbl 

* 輸出 *

Numbers Factorial 
------ --------- 
3 3.00000000000000000000000000000000000001 
5 15.0000000000000000000000000000000000002 

有什麼不對?請幫助

Expected 
-------- 

Numbers Factorial 
------ --------- 
3 6 
5 120 

在此先感謝

+1

看[這篇文章](http://www.club-oracle.com/articles/how-to-get-factorial-in-oracle-159/) –

回答

2

我已經從另一個角度在此一展身手,嘗試做這一切在一個SQL語句(使用表格testTbl和列數)。

這是我想出,看它是否適合你:

SELECT testtbl.numbers, 
     ROUND(EXP(SUM(LN(t1.n)))) AS factorial 
    FROM ( SELECT UNIQUE LEVEL n 
       FROM testtbl 
      CONNECT BY LEVEL <= numbers) t1, 
     ( SELECT UNIQUE LEVEL n 
       FROM testtbl 
      CONNECT BY LEVEL <= numbers) t2, 
     testTbl 
    WHERE t1.n <= t2.n 
    AND t2.n = testTbl.numbers 
    GROUP BY testtbl.numbers 
    ORDER BY testtbl.numbers; 

給人的輸出:

Numbers Factorial 
3  6 
5  120 

希望它可以幫助...

2

要不是我,我會創建一個因子的功能和調用用戶定義的函數在我的查詢。喜歡的東西

SQL> create function factorial(p_n in number) 
    2 return number 
    3 is 
    4 begin 
    5 if(p_n = 1) 
    6 then 
    7  return p_n; 
    8 else 
    9  return p_n * factorial(p_n - 1); 
10 end if; 
11 end; 
12/

Function created. 

SQL> with t as (
    2 select 3 num from dual 
    3 union all 
    4 select 5 from dual 
    5 ) 
    6 select num, 
    7   factorial(num) 
    8 from t; 

     NUM FACTORIAL(NUM) 
---------- -------------- 
     3    6 
     5   120 

如果由於某種原因,你不能定義一個新的功能,你真的想這樣做在SQL中,你將可以生成所有低於表格中的數字號碼,然後聚合這些生成的數字。

SQL> ed 
Wrote file afiedt.buf 

    1 with t as (
    2 select 3 num from dual 
    3 union all 
    4 select 5 from dual 
    5 ) 
    6 select t.num, 
    7   exp(sum(ln(gen.num))) factorial 
    8 from (select level num 
    9   from dual 
10   connect by level <= (select max(t.num) from t)) gen, 
11   t 
12 where gen.num <= t.num 
13* group by t.num 
SQL>/

     NUM FACTORIAL 
---------- ---------- 
     5  120 
     3   6