为什么Postgres的exp / log结果与SQL Server不同? [英] Why the result of exp/log of Postgres differs from SQL Server?

查看:90
本文介绍了为什么Postgres的exp / log结果与SQL Server不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的包装盒上没有SQL Server,但是为什么以下 answer 在Postgres上返回360?

I don't have SQL Server on my box, but why won't the following answer return 360 on Postgres?

select exp(sum(log(val)))
from (values(4),(5),(3),(6)) as tbl(val)

返回12.888075

returns 12.888075

推荐答案

您必须使用自然对数(ln函数),而不是以10为底的对数(log函数):

You have to use natural logarithm (ln function), not base-10 logarithm (log function):

select exp(sum(ln(val)))
from (values(4),(5),(3),(6)) as tbl(val)

 exp 
-----
 360
(1 row)

但这不是乘行的好方法-它很慢,并且由于四舍五入而容易出错。您应该声明一个总计:

But this is not a good way to multiply rows - it is slow and error prone due to rounding. You should declare an aggregate:

create function multiply(int,int) returns int as $$
  select $1*$2;
$$ language sql immutable strict;

create aggregate multiply(int) (
  sfunc=multiply,
  stype=int,
  initcond=1
);

select multiply(val)
from (values(4),(5),(3),(6)) as tbl(val)
 multiply 
----------
      360
(1 row)

这篇关于为什么Postgres的exp / log结果与SQL Server不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆