Re: Select Rows With Only One of Two Values

From: Alban Hertroys <haramrae(at)gmail(dot)com>
To: Chris Angelico <rosuav(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Select Rows With Only One of Two Values
Date: 2012-07-20 20:52:33
Message-ID: B10342CA-AC27-414E-9565-B73561C0BCA3@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 20 Jul 2012, at 18:15, Chris Angelico wrote:

> On Sat, Jul 21, 2012 at 1:53 AM, Rich Shepard <rshepard(at)appl-ecosys(dot)com> wrote:
>> The table has a Boolean indicator column with values of 0 or 1 for each
>> row in the table and another attribute column for parameter names. I need to
>> find all parameter names where the indicator value is only 0 for all rows of
>> that parameter. At least some of the parameters have both rows with 0 and
>> rows with 1 in the indicator attribute. I want to find all (any?) that have
>> only zeros.
>
> Try this:
>
> SELECT DISTINCT param FROM table WHERE indicator=0
> EXCEPT
> SELECT DISTINCT param FROM table WHERE indicator=1

I don't think the DISTINCT is necessary there, doesn't EXCEPT already return a distinct set, just like UNION (hence the existence of UNION ALL)?

It can also be written as a correlated subquery:

SELECT DISTINCT param FROM table t1 WHERE indicator = 0 AND NOT EXISTS (SELECT 42 FROM table t2 WHERE t2.param = t1.param AND indicator <> 0)

(Where 42 is just some placeholder value because the syntax requires it, any value will do but NULL might throw a spanner in the wheels)

Alban Hertroys

--
The scale of a problem often equals the size of an ego.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Alban Hertroys 2012-07-20 21:02:52 Re: A Better Way? (Multi-Left Join Lookup)
Previous Message Tom Lane 2012-07-20 20:46:34 Re: A Better Way? (Multi-Left Join Lookup)