Re: Sum() rows

From: Andrew Hammond <ahammond(at)ca(dot)afilias(dot)info>
To: lucas(at)presserv(dot)org
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Sum() rows
Date: 2005-05-31 21:04:27
Message-ID: 429CD15B.2070503@ca.afilias.info
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

lucas(at)presserv(dot)org wrote:
> Hi.
> How can I sum a row and show the sum for each row???
> For example, in a finances table that have the total movimentation(debit/credit)
> in the bank.
>
> i.e:
> CREATE TABLE TB1 (id integer primary key, value numeric);
> insert into tb1 values (1,20);
> insert into tb1 values (2,2);
> insert into tb1 values (3,3);
> insert into tb1 values (4,17);
> insert into tb1 values (5,-0.5);
> insert into tb1 values (6,3);
>
> I want a query that returns:
> -id- | --- value --- | --- subtot ---
> 1 | 20.00 | 20.00
> 2 | 2.00 | 22.00
> 3 | 3.00 | 25.00
> 4 | 17.00 | 42.00
> 5 | -0.50 | 41.50
> 6 | 3.00 | 44.50
>
> The subtot colum will be the "prev. subtot colum"+"value colum". :-/
> I dont know how to make the "subtot" colum, I tried to use the sum() function
> but it not works correctly.
> Any idea???

This kind of thing is often done using views and rules. For example,

CREATE TABLE tb1_real (
id serial primary key,
value numeric,
subtot numeric
);

CREATE VIEW tb1 AS
SELECT id, value
FROM tb1_real;

CREATE RULE tb1_insert AS
ON INSERT TO tb1 DO INSTEAD
INSERT INTO tb1_real (id, value, subtot)
VALUES (COALESCE(NEW.id, nextval('tb1_real_id_seq')),
NEW.value,
NEW.value + COALESCE((SELECT subtot FROM tb1_real
ORDER BY id DESC LIMIT 1), 0));

/* ahammond(at)[local]:5432/ahammond =# */ INSERT INTO tb1 (value) VALUES (20);
INSERT 60812 1
/* ahammond(at)[local]:5432/ahammond =# */ INSERT INTO tb1 (value) VALUES
(-10);
INSERT 60813 1
/* ahammond(at)[local]:5432/ahammond =# */ SELECT * FROM tb1;
id | value
- ----+-------
1 | 20
2 | -10
(2 rows)

/* ahammond(at)[local]:5432/ahammond =# */ SELECT * FROM tb1_real;
id | value | subtot
- ----+-------+--------
1 | 20 | 20
2 | -10 | 10
(2 rows)

- --
Andrew Hammond 416-673-4138 ahammond(at)ca(dot)afilias(dot)info
Database Administrator, Afilias Canada Corp.
CB83 2838 4B67 D40F D086 3568 81FC E7E5 27AF 4A9A
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.0 (GNU/Linux)

iD8DBQFCnNFZgfzn5SevSpoRAk7ZAJ0aiDO41pajzvD0ioJsUJuaqrbLfACgl1yT
X6WGjU/Vog06apieWmQixF4=
=N5R4
-----END PGP SIGNATURE-----

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Joe Conway 2005-05-31 21:31:16 Re: [SQL] ARRAY() returning NULL instead of ARRAY[] resp. {}
Previous Message Alvaro Herrera 2005-05-31 20:17:11 Re: Sum() rows