Re: sum of array elements

From: Devin Ben-Hur <devin(at)ben-hur(dot)net>
To: Thomas Keller <kellert(at)ohsu(dot)edu>
Cc: Postgresql PDX_Users <pdxpug(at)postgresql(dot)org>
Subject: Re: sum of array elements
Date: 2008-10-24 05:04:52
Message-ID: 49015774.2010406@ben-hur.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pdxpug

Thomas Keller wrote:
> Is there an easy way (succinct) to get the sum of values in an array.
> E.g.
> a260_values is an array of decimal values. And I'd like to get the average.

create or replace function sum_decimal_array( an_array )
returns decimal
as $$
select sum($1[i])
from generate_series(
array_lower($1,1),
array_upper($1,1)
) g(i);
$$ language sql immutable;

select sum_decimal_array( ARRAY[ 1.1, 2.2, 3.3 ] ); -- yeilds 6.6

--
Devin Ben-Hur 503/860-4114 mailto:devin(at)ben-hur(dot)net

"Startups are basically comedies, or at least seem so in retrospect."
-- Paul Graham

In response to

Responses

Browse pdxpug by date

  From Date Subject
Next Message Thomas Keller 2008-10-24 16:36:20 Re: sum of array elements
Previous Message Thomas Keller 2008-10-23 18:23:02 sum of array elements