我有一个包含列号的
表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
提前致谢
答案 0 :(得分: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
答案 1 :(得分: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
希望它有所帮助...