我需要运行一个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
我阅读了很多帖子并尝试了不同的查询无济于事。我认为应该工作的查询如下。有人可以建议替代方案或告诉我查询可能有什么问题吗?
select EmailAddress, CustomerName from Customers
group by EmailAddress, CustomerName
having COUNT(distinct(EmailAddress)) > 1
答案 0 :(得分:197)
这明显快于EXISTS
方式:
SELECT [EmailAddress], [CustomerName] FROM [Customers] WHERE [EmailAddress] IN
(SELECT [EmailAddress] FROM [Customers] GROUP BY [EmailAddress] HAVING COUNT(*) > 1)
答案 1 :(得分:39)
您的查询不正确的是您通过电子邮件和名称进行分组,这组合了每组唯一的电子邮件和名称组合在一起,因此
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)
答案 2 :(得分:10)
怎么样
SELECT EmailAddress, CustomerName FROM Customers a
WHERE Exists ( SELECT emailAddress FROM customers c WHERE a.customerName != c.customerName AND a.EmailAddress = c.EmailAddress)
答案 3 :(得分:9)
select CustomerName,count(1) from Customers group by CustomerName having count(1) > 1
答案 4 :(得分:6)
只是为了好玩,这是另一种方式:
;with counts as (
select CustomerName, EmailAddress,
count(*) over (partition by EmailAddress) as num
from Customers
)
select CustomerName, EmailAddress
from counts
where num > 1
答案 5 :(得分:4)
而不是在where条件中使用子查询,这将增加记录在巨大的查询时间。
我建议使用Inner Join作为此问题的更好选择。
考虑相同的表,这可以给出结果
SELECT EmailAddress, CustomerName FROM Customers as a
Inner Join Customers as b on a.CustomerName <> b.CustomerName and a.EmailAddress = b.EmailAddress
为了获得更好的效果,我建议您使用CustomerID
或您桌子的任何唯一字段。可以复制CustomerName
。
答案 6 :(得分:0)
查询示例:
SELECT [EmailAddress], [CustomerName] FROM [Customers] WHERE [EmailAddress] IN
(SELECT [EmailAddress] FROM [Customers] GROUP BY [EmailAddress] HAVING COUNT(*) > 1);
答案 7 :(得分:0)
SELECT Title, Id
FROM dbo.TblNews
WHERE (Title IN
(SELECT Title
FROM dbo.TblNews AS TblNews_1
GROUP BY Title
HAVING (COUNT(*) > 1)))
ORDER BY Title
答案 8 :(得分:-1)
我正在寻找一个类似的查询,但是我正在寻找客户有多个价值的地方,但是要向多个活跃账户收费。例如:
Customer Account active
------- ------- ------
john 123 y
john 123 y
john 456 y
mary 123 y
mary 123 y
alice 123 n
alice 456 y
所以我希望结果只返回john,因为john是唯一拥有多个处于活动状态的帐户的人。救命!另外,在实际提取数据之前,我想获得记录数。
答案 9 :(得分:-2)
找到非不同的行有一点点变化..
SELECT EmailAddress, CustomerName FROM Customers WHERE EmailAddress NOT IN
(SELECT EmailAddress FROM Customers GROUP BY EmailAddress HAVING COUNT(*) > 1)