X-Original-To: pgsql-sql-postgresql.org@postgresql.org Received: from localhost (mx1.hub.org [200.46.208.251]) by postgresql.org (Postfix) with ESMTP id B900D9FA682 for ; Tue, 25 Jul 2006 17:40:29 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.208.251]) (amavisd-new, port 10024) with ESMTP id 90529-10 for ; Tue, 25 Jul 2006 17:40:24 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey- Received: from floppy.pyrenet.fr (news.pyrenet.fr [194.116.145.2]) by postgresql.org (Postfix) with ESMTP id 3F4039FA65C for ; Tue, 25 Jul 2006 17:40:24 -0300 (ADT) Received: by floppy.pyrenet.fr (Postfix, from userid 106) id 9CA4D30E11; Tue, 25 Jul 2006 22:40:21 +0200 (MET DST) From: "Andrew Hammond" X-Newsgroups: pgsql.sql Subject: Re: reusing AS Date: 25 Jul 2006 13:40:15 -0700 Organization: http://groups.google.com Lines: 38 Message-ID: <1153860015.351799.115210@p79g2000cwp.googlegroups.com> References: Mime-Version: 1.0 Content-Type: text/plain; charset="iso-8859-1" X-Complaints-To: groups-abuse@google.com In-Reply-To: User-Agent: G2/0.2 X-HTTP-UserAgent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.4) Gecko/20060608 Ubuntu/dapper-security Firefox/1.5.0.4,gzip(gfe),gzip(gfe) Complaints-To: groups-abuse@google.com Injection-Info: p79g2000cwp.googlegroups.com; posting-host=207.219.45.62; posting-account=cSUlcA0AAABWACaPjo2Z9C0GBLTio512 To: pgsql-sql@postgresql.org X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0 tagged_above=0 required=5 tests= X-Spam-Level: X-Archive-Number: 200607/310 X-Sequence-Number: 25884 Gregory Stewart wrote: > I am trying to do something like this: > > SELECT SUM(sales_today) AS sales_today_total, SUM(sales_lastweek) AS > sales_lastweek_total > CASE WHEN sales_today_total = '0' THEN '0'::int4 WHEN sales_lastweek_total = > '0' THEN '0'::int4 ELSE ((100/sales_today_total*sales_lastweek_total)-100) > END AS variance > FROM mytable > > I am getting the message that the column 'sales_today_total' and > 'sales_lastweek_total' do not exist. It looks like I can't reference the > aliases I defined (sales_today_total, sales_lastweek_total). That is correct. Use a sub-query: SELECT sales_today_total, sales_lastweek_total, CASE WHEN sales_today_total = 0 THEN 0 WHEN sales_lastweek_total = 0 THEN 0 ELSE ((100/sales_today_total*sales_lastweek_total)-100) END AS variance FROM (SELECT SUM(sales_today) AS sales_today_total, SUM(sales_lastweek) AS sales_lastweek_total FROM yourtable); > The reason I am asking is my actual SQL query is rather long with a few > dozen SUM functions, most of them being reused within the query for > calculations. I just don't want Postgresql to calculate the same thing over > and over again and getting the same results and wasting resources. It won't if you 1) Don't use volatile functions (obviously) 2) Don't force recalculation by correlating your sub-queries. Drew