PostgreSQL function is huge, to achieve multiplication this kind of operation has many methods, today I will briefly enumerate the following several convenient ways.
Like we're counting 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, Ten Nt_girl (# Union Allt_girl (# Select M*n, (n-1) n from G where n > 1t_girl (#) t_girl-# select Max (m) as factorial_10 from G; Factorial_10--------------3628800 (1 row) time:3.893 ms
3. Use simple functions 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 (Ten) as factorial_10; Factorial_10--------------3628800 (1 row) time:1.022 ms
4. Use cursors 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 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 (10) factorial_10; factorial_10 -------------- 3628800 (1 Row) Time: 2.238 mst_girl=#
5. Use custom Python functions
Create or Replace function func_get_factorial_py (f_number int) returns bigint as $ytt $m = 1n = 1for i in range (1,f_number +1): M = m * in = Mreturn n$ytt$ language plpythonu;t_girl=# Select Func_get_factorial_py (Ten) factorial_10; Factorial_10--------------3628800 (1 row) time:1.060 ms
This article is from "God, we don't see!" "Blog, be sure to keep this provenance http://yueliangdao0608.blog.51cto.com/397025/1575574
"Original" PostgreSQL implementation Factorial method enumeration