How to Select Every Row Where Column Value is NOT Distinct
I need to run a select statement that returns all rows where the value of a column is not distinct (e.g. EmailAddress).
For example, if the table looks like below:
CustomerName EmailAddress
Aaron [email protected]
Christy [email protected]
Jason [email protected]
Eric [email protected]
John [email protected]
I need the query to return:
Aaron [email protected]
Christy [email protected]
John [email protected]
I have read many posts and tried different queries to no avail. The query that I believe should work is below. Can someone suggest an alternative or tell me what may be wrong with my query?
select EmailAddress, CustomerName from Customers
group by EmailAddress, CustomerName
having COUNT(distinct(EmailAddress)) > 1
This is significantly faster than the EXISTS
way:
SELECT [EmailAddress], [CustomerName] FROM [Customers] WHERE [EmailAddress] IN
(SELECT [EmailAddress] FROM [Customers] GROUP BY [EmailAddress] HAVING COUNT(*) > 1)
The thing that is incorrect with your query is that you are grouping by email and name, that forms a group of each unique set of email and name combined together and hence
aaron and [email protected]
christy and [email protected]
john and [email protected]
are treated as 3 different groups rather all belonging to 1 single group.
Please use the query as given below :
select emailaddress,customername from customers where emailaddress in
(select emailaddress from customers group by emailaddress having count(*) > 1)
select CustomerName,count(1) from Customers group by CustomerName having count(1) > 1
How about
SELECT EmailAddress, CustomerName FROM Customers a
WHERE Exists ( SELECT emailAddress FROM customers c WHERE a.customerName != c.customerName AND a.EmailAddress = c.EmailAddress)