Received: from localhost (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 1770F4768EA for ; Mon, 2 Dec 2002 14:43:53 -0500 (EST) Received: from temp.joelburton.com (65.eebed1.client.atlantech.net [209.190.238.101]) by postgresql.org (Postfix) with ESMTP id 696994768B8 for ; Mon, 2 Dec 2002 14:23:21 -0500 (EST) Received: by temp.joelburton.com (Postfix, from userid 501) id B18842BA27; Mon, 2 Dec 2002 14:23:21 -0500 (EST) Date: Mon, 2 Dec 2002 14:23:21 -0500 From: Joel Burton To: Casey Allen Shobe Cc: pgsql-sql@postgresql.org Subject: Re: Combining queries while preserving order in SQL - Help! Message-ID: <20021202192321.GA13619@temp.joelburton.com> References: <200212021346.38338.cshobe@osss.net> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <200212021346.38338.cshobe@osss.net> User-Agent: Mutt/1.3.25i X-Virus-Scanned: by AMaViS new-20020517 X-Archive-Number: 200212/15 X-Sequence-Number: 10603 On Mon, Dec 02, 2002 at 01:46:38PM -0500, Casey Allen Shobe wrote: > Hi there, > > I need to do the following in one SQL query: > > select field1, field2, field3, field4, field5 from table where field6 < 5 > order by field1 > > And a totals line which shows the sum for each column. > > The important part is that I need to preserve the order by of the first query. > > Is there any way to do this in one query? create table foo (a int, b int, c int ); insert into foo values (1,2,3); insert into foo values (4,5,6); select '' as label, * from foo union all select 'TOTAL', sum(a), sum(b), sum(c) from foo order by 1,2; (you wouldn't need the label column to sort by, except that a might contain negative numbers, so the sum might be _less_ than some/all of the numbers. by first sorting on this junk column, we can force the totals at the bottom). p.s. don't forget the "union __all__", otherwise you'll get rid of duplicate entries in the your table. -- Joel BURTON | joel@joelburton.com | joelburton.com | aim: wjoelburton Independent Knowledge Management Consultant