Skip to content
Advertisement

How to check if two columns are consistent in a table. sql

I’m struggling to ask the question so I will just put an example table. Basically, if I have two columns with headings person and insured car, how can I check if the same person consistently insures the same brand of car.

 ------|------
|person|brand |
 ------|------
|  0   |Toyota|
|  0   |Mazda |
|  1   |Toyota|
|  1   |Toyota|
|  2   |Honda |
|  2   |Honda |
|  3   |Ford  |
 ------|------

So basically in this table I want to filter out person 0 because he insures both Toyota’s and Mazda’s, however the other people exclusively insure one brand of a car.

Thanks.

Advertisement

Answer

If you just want the people and car, you can use aggregation:

select person, min(brand) as the_brand
from t
group by person
having min(brand) = max(brand);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement