Reputation: 1065
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?
Upvotes: 1
Views: 61
Reputation: 72165
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))
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
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(*)
Upvotes: 3