Received: from sss.pgh.pa.us ([192.204.191.242]) by postgresql.org (8.11.3/8.11.1) with ESMTP id f4TEotE28340 for ; Tue, 29 May 2001 10:50:55 -0400 (EDT) (envelope-from tgl@sss.pgh.pa.us) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.11.3/8.11.3) with ESMTP id f4TEolR18587; Tue, 29 May 2001 10:50:47 -0400 (EDT) To: "Tim Barnard" cc: "Jim" , pgsql-general@postgresql.org Subject: Re: Re: [SQL] Difficult SQL Statement In-reply-to: <18343.991143963@sss.pgh.pa.us> References: <01f101c0e7c6$9fc061a0$a519af3f@hartcomm.com> <18343.991143963@sss.pgh.pa.us> Comments: In-reply-to Tom Lane message dated "Tue, 29 May 2001 09:46:03 -0400" Date: Tue, 29 May 2001 10:50:46 -0400 Message-ID: <18584.991147846@sss.pgh.pa.us> From: Tom Lane X-Archive-Number: 200105/1135 X-Sequence-Number: 10185 I wrote: > select ASMT_CODE, PASSED, TOTAL, PASSED::float4/TOTAL::float4 > from > (select ASMT_CODE, count(*) as TOTAL from RESULTS > group by ASMT_CODE) as tmp1 > natural join > (select ASMT_CODE, count(*) as PASSED from RESULTS > where STATUS='PASSED' group by ASMT_CODE) as tmp2 BTW, although this is a fine example of how to avoid using temp tables, it's not such a great solution to the original problem. What happens if there are no 'PASSED' entries at all for a given ASMT_CODE? You probably won't want that ASMT_CODE to disappear from your report --- but it will disappear in the join. We could fix this with a left join and some hackery to deal with the resulting NULL values for PASSED, but now things are getting ugly. Time to try something different: select ASMT_CODE, PASSED, TOTAL, PASSED::float4/TOTAL::float4 as PCT from (select ASMT_CODE, count(*) as TOTAL, sum(CASE WHEN STATUS='PASSED' THEN 1 ELSE 0 END) as PASSED from RESULTS group by ASMT_CODE) as tmp1 Here we use the sub-select only as a way of labeling the count() and sum() results so that we don't have to write and compute them twice. You could write it as a simple one-level SELECT if you didn't mind that redundancy. regards, tom lane