Received: from megazone.bigpanda.com (megazone.bigpanda.com [63.150.15.178]) by postgresql.org (Postfix) with ESMTP id 124BD474E49 for ; Wed, 31 Jul 2002 20:23:21 -0400 (EDT) Received: by megazone.bigpanda.com (Postfix, from userid 1001) id CCD8FD5F7; Wed, 31 Jul 2002 17:23:22 -0700 (PDT) Received: from localhost (localhost [127.0.0.1]) by megazone.bigpanda.com (Postfix) with ESMTP id AA6AB5C04; Wed, 31 Jul 2002 17:23:22 -0700 (PDT) Date: Wed, 31 Jul 2002 17:23:22 -0700 (PDT) From: Stephan Szabo To: Tom Haddon Cc: Subject: Re: FW: Case Statement In-Reply-To: Message-ID: <20020731172012.W22782-100000@megazone23.bigpanda.com> MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII X-Archive-Number: 200207/466 X-Sequence-Number: 8844 On Wed, 31 Jul 2002, Tom Haddon wrote: > Hi Stephan, > > I have a lot of fields, so I'm not sure if a function or case is the way to > go. Basically, I have, say 50 boolean fields that are being evaluated, and I > want to have a column which is the sum of the number of "TRUE" values of > those 50 columns, and then ORDER BY that column. So, for example of the 50 > fields to be evaluated, the SELECT statement should return records ordered > by those that match the most number of criteria. Does that make sense? Your > example below may actually work for me, on the other hand: > > "case when field1 is true then 1 else 0 end + > case when field2 is true then 2 else 0 end + > case when field3 is true then 4 else 0 end > > Let's suppose field1 is true and field2, field3 are not, would it return 1, > and if all three are true it would return 7 for the case? If so, I think > that's the way to go, as all this is being dynamically built in any case. Yes, that's what it should do (I did the 2 variable case and all 4 combinations to try getting all 0-3). If you're doing many more selects than update/inserts to the table where you want to do this (and the fields you care about is a constant set) then a trigger on insert/update is the way to go and just store the value.