PostgreSQL中的产品聚合

时间:2012-10-31 10:41:19

标签: sql postgresql aggregate

我尝试在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),

谢谢

2 个答案:

答案 0 :(得分:7)

将您的输入从double precisionfloat8)投放到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版本(float8double 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)