views:

74

answers:

1

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)

returns 12.888075

+2  A: 

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)
Tometzky
:-) something for other rdbms users to envy about, i'll post your answer on this question http://stackoverflow.com/questions/1490433/performing-multiplication-in-sql-serverset-based-approach
Hao
:-) can you edit your question? so as to convince other rdbms users that postgresql is uber-flexible. add this: select val, multiply(kyrie)from (values(1,4),(8,5),(1,3),(8,6),(1,2)) as tbl(val, kyrie)group by val order by val
Hao