Shilpa Bharkhada Shilpa Bharkhada - 17 days ago 8
SQL Question

How to select rows only if column values are same?

I have a table like below

City Status
a y
a y
a y
b n
b n
b y
c y
c n
d n
d n


I want the result to be returned as

City Status
a y
a y
a y
d n
d n


Group by city but whose all status value should be same for that city.

How can I do this?

Answer

You can use NOT EXISTS() :

SELECT * 
FROM YourTable t
WHERE NOT EXISTS(SELECT 1 FROM YourTable s
                 WHERE t.city = s.city AND
                       t.status <> s.status)
Comments