0

I have 2 tables:

people

    person_id int
    FirstName varchar
    LastName  varchar

people_codes

    person_id int
    code varchar
    primary bit

If I join the tables I get something like this:

    firstName   lastName   code   primary
    -------------------------------------
    John        Smith      GEN    0
    John        Smith      VAS    1
    Aaron       Johnson    ANE    0
    Allison     Hunt       HOS    0

Ok, so here's the question. How do I query for only the people that have a primary bit of only a 0?

In the above results I only want Aaron and Allison to return, because John Smith has a primary occurrence of 1. Essentially, I can't just say where primary = 0 because I would still get John.

Thank you,

Trout

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Trout
  • 3
  • 1

4 Answers4

1
SELECT FirstName, LastName 
FROM dbo.people AS p
WHERE EXISTS
(
  SELECT 1 FROM dbo.people_codes
    WHERE person_id = p.person_id
    GROUP BY person_id
    HAVING MAX(CONVERT(TINYINT, [primary]) = 0)
);
Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490
1

I recommend using a Not Exists statement, like this:

Select FirstName, LastName
From people
    -- <optional join to other tables>
Where Not Exists
(
    Select 1
    From people_codes
    Where primary = 1
        And people.person_id = people_codes.person_id
)

Why do you want to you use Not Exists? See: NOT IN vs NOT EXISTS

Community
  • 1
  • 1
Mike
  • 3,641
  • 3
  • 29
  • 39
0

select * from people p, people_codes c where p.person_id = c.person_id and p.person_id not in (select person_id from person_codes where primary = 1)

replace * with desired columns, include alias (p.FirstName)

Konstantin
  • 3,254
  • 15
  • 20
0

try this

Select distint firstName, lastName  , code   ,primary
From people 
    Inner Join people_codes on people.person_id = people_codes.person_id 
Where people.person_id NOT IN (select person_id 
                               from people_codes 
                               where primary=1)
huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99