PostgreSQL function is huge, to realize multiplication such operations have a lot of methods, today I would like to simply enumerate the following several convenient ways.
Like we're going to count 10!
1, you can use SQL to expand it:
t_girl=# Select 1*2*3*4*5*6*7*8*9*10 as multiply_10;
Multiply_10
------------
3628800
(1 row)
time:0.854 ms
2. With recursion
t_girl=# with recursive g (m,n) as
t_girl-# (select 1 m, n
T_girl (# UNION ALL
T_girl (# Select M*n, (n-1) n from g where n > 1
T_girl (#)
t_girl-# select Max (m) as factorial_10 from G;
Factorial_10
--------------
3628800
(1 row)
time:3.893 ms
3, with a simple function to expand
Create or Replace function func_get_factorial (
F_number int
) returns bigint
As
$ytt $
declare i int: = 1;
DECLARE v_result bigint: = 1;
Begin
For I in 1. F_number Loop
V_result: = V_result * i;
End Loop;
return v_result;
End
$ytt $
Language plpgsql;
t_girl=# Select Func_get_factorial (a) as factorial_10;
Factorial_10
--------------
3628800
(1 row)
time:1.022 ms
4, with the cursor and sequence function generate_series to expand
Create or Replace function Func_get_factorial2 (
F_number int
) returns bigint
As
$ytt $
Declare CS1 cursor for select n from Generate_series (1,f_number,1) as g (n);
DECLARE v_result bigint: = 1;
DECLARE v_n bigint: = 0;
Begin
Open CS1;
Loop
Fetch CS1 into v_n;
Exit when is not found;
V_result: = V_result * V_N;
End Loop;
Close CS1;
return v_result;
End
$ytt $
Language plpgsql;
t_girl=# Select Func_get_factorial2 (a) factorial_10;
Factorial_10
--------------
3628800
(1 row)
time:2.238 ms
t_girl=#
5. Use custom Python functions
Create or Replace function func_get_factorial_py (
F_number int
) returns bigint
As
$ytt $
m = 1
n = 1
For I in Range (1,f_number+1):
m = m * I
n = m
return n
$ytt $
Language Plpythonu;
t_girl=# Select Func_get_factorial_py (a) factorial_10;
Factorial_10
--------------
3628800
(1 row)
time:1.060 ms