简体   繁体   中英

Find rows that have one column value same but not the other

I have a table structure like this:

ProductId | Parentid | Name

1 | 1 | Abc

2 | 1 | Abc

3 | 2 | Xyz

4 | 3 | Xyz

5 | 3 | Abc

I need a query which finds such rows which have parentid as the same as the other rows but different name than the other.

For an example: Query should fetch below result, because parentid is same for both rows but name is not the same.

4 | 3 | Xyz

5 | 3 | Abc

Can somebody help forming the query?

One way is this:

SELECT ProductId, ParentId, Name
FROM mytable 
WHERE ParentId IN (
  SELECT Parentid
  FROM mytable
  GROUP BY Parentid
  HAVING MIN(Name) <> MAX(Name))

SQL Fiddle Demo

You can alternatively use INNER JOIN :

SELECT ProductId, m.ParentId, Name
FROM mytable m
INNER JOIN (SELECT Parentid
            FROM mytable
            GROUP BY Parentid
            HAVING MIN(Name) <> MAX(Name)) t
ON m.ParentId = t.ParentId            

SQL Fiddle Demo

As a final note, if you want all values in Name column to be distinct, then you have to use the following HAVING clause:

HAVING COUNT(*) > 1  AND COUNT(DISTINCT Name) = COUNT(*)

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