Received: from kss.net.au ([203.41.122.41]) by mail.postgresql.org (8.11.1/8.11.1) with ESMTP id f0I42B095065 for ; Wed, 17 Jan 2001 23:02:14 -0500 (EST) (envelope-from carolyn@greatpacific.com.au) Received: from greatpacific.com.au (coco [10.10.1.9]) by kss.net.au (8.8.7/8.8.7) with ESMTP id PAA06860; Thu, 18 Jan 2001 15:01:29 +1100 Message-ID: <3A666A8F.591B8315@greatpacific.com.au> Date: Thu, 18 Jan 2001 15:01:19 +1100 From: Carolyn Lu Wong Organization: Great Pacific Financial Group X-Mailer: Mozilla 4.75 [en] (WinNT; U) X-Accept-Language: en MIME-Version: 1.0 To: Tom Lane CC: "pgsql-sql@postgresql.org" Subject: Re: update help References: <3A665AE3.CE43178B@greatpacific.com.au> <22930.979787939@sss.pgh.pa.us> Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Archive-Number: 200101/206 X-Sequence-Number: 871 Forgot to mention that I'm using V6.5. It doesn't seem to like subqueries, got the following error: ERROR: parser: parse error at or near "select" What I really want to do is follows t2: ID Amount ........ ----------------------- 1 1 ...... 1 2 ...... 2 3 ...... 2 2 ...... and want the following result in t1 t1: ID Amount ....... ----------------------- 1 3 ...... 2 5 ...... Tom Lane wrote: > > Carolyn Wong writes: > > I'd like to know what's the correct SQL statement to do the following: > > update t1 a > > set a.amount = sum(b.amount) > > from t2 b > > where a.id = b.id > > Try > > UPDATE t1 SET amount = (select sum(b.amount) from t2 b WHERE t1.id = b.id); > > Or possibly you want > > UPDATE t1 SET amount = (select sum(b.amount) from t2 b WHERE t1.id = b.id) > WHERE EXISTS (select * FROM t2 b WHERE t1.id = b.id); > > depending on whether you mean to zero out any t1 rows that have no > matching rows in t2. Note that you cannot attach an alias name to the > target table, you have to use its real name in the subselects. > > There was a thread about this very issue a few months ago, and IIRC > we decided that an aggregate in an UPDATE doesn't have well-defined > semantics. The SQL92 spec explicitly disallows it. Right now PG will > take it, but we probably do something pretty surprising :-( > > regards, tom lane