Re: aggregate function ? - Mailing list pgsql-novice

From Richard Broersma Jr
Subject Re: aggregate function ?
Date
Msg-id 183533.40800.qm@web31802.mail.mud.yahoo.com
Whole thread Raw
In response to aggregate function ?  (Raimon Fernandez <coder@montx.com>)
List pgsql-novice
--- Raimon Fernandez <coder@montx.com> wrote:

> hi again,
>
>
> Some days ago I asked for help, nobody replied, and after trying to
> do it in some way, I think aggregate function is the solution to my
> problem, but I found difficult to understand how it works ...
>
> What I want to do is accumulate the value for each row and add it to
> the next:
>
> a 100 100
> b 50 150
> c 25 175
>
One solution is to use a correlated sub-query:

  SELECT A.letter_field, A.letter_value,
         ( SELECT sum( letter_value )
             FROM Your_table AS B
            WHERE B.letter_field <= A.letter_field ) AS value_sum
    FROM Your_table AS A
ORDER BY A.letter_field;

Another solution is to use a join:

    SELECT A.letter_field, A.letter_value,
           sum( B.letter_value ) AS value_sum
      FROM Your_table AS A
INNER JOIN Your_table AS B
        ON A.letter_field <= B.letter_field
  GROUP BY A.letter_field, A.letter_value,
  ORDER BY A.letter_field;

There are a couple of good SQL books that are really good at teaching methods on how to construct
such queries if you are enterested.

Regards,
Richard Broersma Jr.


pgsql-novice by date:

Previous
From: "Neil Saunders"
Date:
Subject: Re: Invalid byte sequence for encoding "UTF8"
Next
From: Raimon Fernandez
Date:
Subject: Re: aggregate function ?