简体   繁体   中英

SQL - How to identify table rows that don't match what's normally in that column of the table

I'm having a difficult time trying to figure out how to devise a query that will locate a row in a table that doesn't contain values that usually show up for that column.

For example, let's say I have the following table:

在此处输入图像描述

Let's say I have 2000 unique Box Numbers, that have handful of numbered balls in them with what color they are. For the most part, all boxes should only have one color type in them (let's say there are a total of 256 colors), but there are some that have more than one color in them.

What I'm trying to achieve here is to develop a query that will find which boxes have more than one color inside it.

develop a query that will find which boxes have more than one color inside it

If you want entire rows, you can use exists :

select t.*
from mytable t
where exists (
    select 1 from mytable t1 where t1.box_number = t.box_number and t1.color <> t.color
)

If you just want the box numbers, then I would prefer group by and having :

select box_number
from mytable t
group by box_number
having min(color) <> max(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