postgresql 功能龐大,對實現乘法這類運算有諸多的方法,今天我來簡單列舉下以下幾種便捷的途徑。
比如我們要計算10!
1、 可以用sql給它展開:
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遞迴
t_girl=# with recursive g(m,n) as
t_girl-# (select 1 m, 10 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、 用簡單的函式來展開
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(10) as factorial_10;
factorial_10
--------------
3628800
(1 row)
time: 1.022 ms
4、 用游標和序列函式generate_series來展開
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 ms
t_girl=#
5、 用自定義python函式
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(10) factorial_10;
factorial_10
--------------
3628800
(1 row)
time: 1.060 ms
原創 PostgreSQL 實現階乘方法列舉
postgresql 功能龐大,對實現乘法這類運算有諸多的方法,今天我來簡單列舉下以下幾種便捷的途徑。比如我們要計算10!1 可以用sql給它展開 t girl select 1 2 3 4 5 6 7 8 9 10 as multiply 10 multiply 10 3628800 1 row ...
原創 PostgreSQL 對陣列的遍歷
postgresql 提供了陣列型別。我來演示下如何具體使用。建立乙個有陣列型別欄位的表。create table test array id serial primary key,str1 int 插入兩條測試資料。insert into test array values 1,array 1,2...
原創 PostgreSQL 對陣列的遍歷
postgresql 提供了陣列型別。我來演示下如何具體使用。建立乙個有陣列型別欄位的表。create table test array id serial primary key,str1 int 插入兩條測試資料。insert into test array values 1,array 1,2...