Re: summing tables

From: Erik Thiele <erik(at)thiele-hydraulik(dot)de>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: summing tables
Date: 2003-07-15 12:39:25
Message-ID: 20030715143925.54716ed4.erik@thiele-hydraulik.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Tue, 15 Jul 2003 15:16:21 +0300
"Viorel Dragomir" <bigchief(at)vio(dot)ro> wrote:

> update table_name
> set c = a + b + (select c from table_name as x where x.seq = seq-1)
> where c is null;

hmmm. the query is run row by row, isn't it?
but it will have different results depending on the order of those rows.

look, the c value is set by one row-query
and read by the row-query of the row below.

does sql specify some "order is magically always as you expect it" rule?

still i am a little confused.

and i am sorry, i didn't initially specify that the "seq" are not gapless.
i.e. seq-1 does not always exist. but seq-13 could be the next lower one!

zeit=# select * from foo;
seq | a | b | c
-----+----+----+---
0 | 1 | 2 | 3
1 | 1 | 2 |
2 | 5 | 7 |
3 | -2 | -4 |
6 | -1 | -2 |
5 | -2 | -2 |
4 | 0 | 1 |
(7 rows)

i created this (gapless for easiness) table and run your query:

zeit=# update foo set c = a + b + (select c from foo as x where x.seq = seq-1) where c is null;
UPDATE 6

#### 6 updates??? really???

zeit=# select * from foo;
seq | a | b | c
-----+----+----+---
0 | 1 | 2 | 3
1 | 1 | 2 |
2 | 5 | 7 |
3 | -2 | -4 |
6 | -1 | -2 |
5 | -2 | -2 |
4 | 0 | 1 |
(7 rows)

hmmmm. let's try the statement of the other reply to my initial mail:

UPDATE foo t set c = a + b + (Select c from foo tt where tt.seq = t.seq -1)

zeit=# UPDATE foo t set c = a + b + (Select c from foo tt where tt.seq = t.seq -1);
ERROR: parser: parse error at or near "t"

hmmmm....

any clues?

cu & thx
erik

> additional checks are required if you want to update c when c is not null
> if all the c are null then this query will do nothing
> > i have a table consisting of 4 integers.
> >
> > seq is for making the table ordered. (ORDER BY SEQ ASC)
> > a,b,c maybe null
> >
> >
> > seq | a | b | c
> > -----+----+----+---
> > 0 | 1 | 2 | 3
> > 1 | 1 | 2 |
> > 2 | 5 | 7 |
> > 3 | -2 | -4 |
> >
> >
> > i am needing a sql statement to do
> >
> > c=a+b+"the c of the row with seq one less than myself"
> >
> > this statement has to run over the whole table, in seq order.

--
Erik Thiele

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Jan Bernhardt 2003-07-15 12:44:38 Non-Blocking Locks (i.e. Oracle NOWAIT)
Previous Message Dani Oderbolz 2003-07-15 12:17:50 Re: summing tables