我尝试在PostgreSQL中为product(*)创建聚合。 我的行的字段类型是“双精度”
所以,我试过了:
CREATE AGGREGATE nmul(numeric)
(
sfunc = numeric_mul,
stype = numeric
);
当我启动查询时,结果为:
ERROR: function nmul(double precision) does not exist
LINE 4: CAST(nmul("cote") AS INT),
谢谢
答案 0 :(得分:7)
将您的输入从double precision
(float8
)投放到numeric
,或定义汇总的double precision
风格。
您的聚合工作正常:
regress=> CREATE AGGREGATE nmul(numeric)
regress-> (
regress(> sfunc = numeric_mul,
regress(> stype = numeric
regress(> );
regress=> SELECT nmul(x) FROM generate_series(1,100) x;
nmul
----------------------------------------------------------------------------------------------------------------------------------------------------------------
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
(1 row)
问题是您的查询:
regress=> SELECT nmul(x::float8) FROM generate_series(1,100) x;
ERROR: function nmul(double precision) does not exist
LINE 1: SELECT nmul(x::float8) FROM generate_series(1,100) x;
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
您可以定义汇总的float8
版本(float8
是double precision
的同义词):
regress=> CREATE AGGREGATE nmul(double precision)
(
sfunc = float8mul,
stype = float8
);
regress=> SELECT nmul(x::float8) FROM generate_series(1,100) x;
fmul
-----------------------
9.33262154439441e+157
(1 row)
如果要保留值的完整精度,请在聚合之前或强制转换为numeric
,例如:
CAST(nmul(CAST("cote" AS numeric)) AS INT)
或PostgreSQL特有的速记:
nmul("cote"::numeric)::integer
请注意,当您使用这些产品聚合时,integer
会很快溢出:
regress=> SELECT nmul(x)::integer FROM generate_series(1,12) x;
nmul
-----------
479001600
(1 row)
regress=> SELECT nmul(x)::integer FROM generate_series(1,13) x;
ERROR: integer out of range
regress=>
所以你可能想要坚持使用numeric
。
答案 1 :(得分:6)
我找到了一个非常聪明的人的解决方案,他意识到你可以用对数来实现这个目标(credit goes to him):
select exp(sum(ln(x))) from generate_series(1,5) x;
exp
-----
120
(1 row)