SQL - 选择具有相同电子邮件但名称不同的所有行

时间:2015-03-24 16:52:38

标签: sql select count group-by duplicates

我尝试选择表格中具有相同Email但具有不同Name的所有用户。到目前为止,我已设法获取所有重复Email的行,但我仍然坚持下一步。

SELECT * FROM users WHERE Email IN
(SELECT Email FROM users GROUP BY Email HAVING COUNT(*) > 1) 

提前致谢

3 个答案:

答案 0 :(得分:3)

我认为您只想在子查询中使用count(distinct name)

SELECT *
FROM users
WHERE Email IN (SELECT Email
                FROM users
                GROUP BY Email
                HAVING COUNT(distinct Name) > 1
               ) ;

我更喜欢having min(name) <> max(name)条款having。效率稍高。

但是,最有效的方法可能是使用窗口函数:

select u.*
from (select u.*, min(name) over (partition by email) as minname,
             max(name) over partition by email) as maxname
      from users u
     ) u
where minname <> maxname;

答案 1 :(得分:1)

您可以尝试以下操作:

SELECT u.* 
FROM users u
LEFT JOIN (
   SELECT Email  
   FROM users
   GROUP BY Email 
   HAVING COUNT(*) = COUNT(DISTINCT name)
) tmp ON u.Email = tmp.Email
WHERE tmp.Email IS NOT NULL

答案 2 :(得分:1)

试试这个

SELECT * 
FROM users U1
INNER JOIN 
users U2
on U1.Email=U2.Email
AND U1.Name <> U2.Name