简体   繁体   中英

sql query in exact match

let's say I have the following table

name | color
-------------
jon    blue
jon    black
jon    red
bill   blue
bill   red
jack   blue
....

I'd like to run a query to get all names with only colors = blue and red and same thing for a qeyry with all names where color = blue only (no black, no red)

I've tried something like below

select name, color from table where color in ('blue', 'red')
group by name, color

but it gives me more results than I expect... Any ideas ?

Thanks !

  select name
    from tbl
   where color in ('blue','red')
     and not exists (select * from tbl t2
                     where t2.name=tbl.name and t2.color NOT IN ('blue','red'))
group by name
  having count(distinct color) = 2

Let try this query:

SELECT name, color
FROM table1
WHERE name IN
(
    SELECT name
    FROM table1 t1
    WHERE color IN ('blue', 'red')
      AND NOT EXISTS
      (
         SELECT * 
         FROM table1 t2 
         WHERE t1.name = t2.name
           AND t2.color NOT IN ('blue', 'red')
       )
    GROUP BY name
    HAVING COUNT(DISTINCT color) = 2 --to be sure only red won't be accepted

    UNION

    SELECT name
    FROM table1 t1
    WHERE color = 'blue'
     AND NOT EXISTS
     (
        SELECT * 
        FROM table1 t2 
        WHERE t1.name = t2.name
          AND t2.color <> 'blue'
     )
)
ORDER BY name, color

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM