[英]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. 我需要一个查询来查找这样的行,这些行的parentid与其他行相同但名称不同于另一行。
For an example: Query should fetch below result, because parentid is same for both rows but name is not the same. 例如:查询应该获取下面的结果,因为两个行的parentid相同但名称不相同。
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))
You can alternatively use INNER JOIN
: 您也可以使用
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: 最后要注意的是,如果您希望
Name
列中的所有值都是不同的,那么您必须使用以下HAVING
子句:
HAVING COUNT(*) > 1 AND COUNT(DISTINCT Name) = COUNT(*)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.