如何select列值不相同的每一行

我需要运行一个select语句来返回列的值不是不同的所有行(例如EmailAddress)。

例如,如果表格如下所示:

CustomerName EmailAddress Aaron aaron@gmail.com Christy aaron@gmail.com Jason jason@gmail.com Eric eric@gmail.com John aaron@gmail.com 

我需要查询返回:

 Aaron aaron@gmail.com Christy aaron@gmail.com John aaron@gmail.com (peer edited from john@gmail.com) 

我读了很多post,尝试了不同的查询无济于事。 我认为应该工作的查询如下。 有人可以提出一个替代scheme或告诉我什么可能是我的查询错?

 select EmailAddress, CustomerName from Customers group by EmailAddress, CustomerName having COUNT(distinct(EmailAddress)) > 1 

这比EXISTS方式快得多:

 SELECT [EmailAddress], [CustomerName] FROM [Customers] WHERE [EmailAddress] IN (SELECT [EmailAddress] FROM [Customers] GROUP BY [EmailAddress] HAVING COUNT(*) > 1) 

你的查询不正确的事情是,你是通过电子邮件和名称分组,形成一组每个独特的电子邮件和名称组合在一起,因此

 aaron and aaron@gmail.com christy and aaron@gmail.com john and aaron@gmail.com 

被视为3个不同的组,而全部属于1个单独的组。

请使用下面的查询:

 select emailaddress,customername from customers where emailaddress in (select emailaddress from customers group by emailaddress having count(*) > 1) 

怎么样

 SELECT EmailAddress, CustomerName FROM Customers a WHERE Exists ( SELECT emailAddress FROM customers c WHERE a.customerName != c.customerName AND a.EmailAddress = c.EmailAddress) 
 select CustomerName,count(1) from Customers group by CustomerName having count(1) > 1 

只是为了好玩,这是另一种方式:

 ;with counts as ( select CustomerName, EmailAddress, count(*) over (partition by EmailAddress) as num from Customers ) select CustomerName, EmailAddress from counts where num > 1 

而不是在where条件下使用子查询,这将增加查询时间,其中logging是巨大的。

我build议使用Inner Join作为这个问题的更好的select。

考虑到同一个表,这可能会给出结果

 SELECT EmailAddress, CustomerName FROM Customers as a Inner Join Customers as b on a.CustomerName <> b.CustomerName and a.EmailAddress = b.EmailAddress 

为了更好的结果,我build议你使用CustomerID或你的表的任何独特的领域。 CustomerName名称的重复是可能的。

那么有一个轻微的变化,find不明显的行..

SELECT EmailAddress,CustomerName FROM Customers WHERE EmailAddress NOT IN(SELECT EmailAddress FROM Customers GROUP BY EmailAddress HAVING COUNT(*)> 1)