在表

时间:2017-11-15 19:42:11

标签: sql sql-server

我只是浏览了这个post并尝试了所有的脚本,但我仍然没有得到我所期待的。

这是我的表

Name        email
BRIAN MAT   BRIAN.MAT@abc.Com
BRIAN MAT   BRIAN MAT@abc.Com
AMY Lee     AMY.Lee@abc.Com
AMY.Lee     AMY.Lee@abc.Com
Madison Taylor  Madison.Tyl@abc.com


SELECT Name 
FROM Employee
GROUP BY Name 
HAVING ( COUNT(Name > 1 )

结果

BRIAN MAT

SELECT email
FROM Employee
GROUP BY email
HAVING ( COUNT(email> 1 )

结果

AMY.Lee@abc.Com

我试图将这两个脚本分组,但它显示空白

SELECT
    Name, email,COUNT(*)
FROM
    Employee
GROUP BY
    Name, email
HAVING 
    COUNT(*) > 1

请在我的脚本中纠正我所缺少的内容,以获得如下结果

Name        email
BRIAN MAT   BRIAN.MAT@abc.Com
BRIAN MAT   BRIAN MAT@abc.Com
AMY Lee     AMY.Lee@abc.Com
AMY.Lee     AMY.Lee@abc.Com

3 个答案:

答案 0 :(得分:2)

SELECT *
FROM Employee
WHERE Name IN (SELECT Name 
               FROM Employee
               GROUP BY Name 
               HAVING COUNT(Name > 1) 
              )
   OR Email IN (SELECT email
                FROM Employee
                GROUP BY email
                HAVING COUNT(email> 1)
              )

答案 1 :(得分:2)

您可以使用窗口COUNT

WITH cte  AS (
   SELECT *,
         COUNT(*) OVER(PARTITION BY name)  AS c_name,
         COUNT(*) OVER(PARTITION BY Email) AS c_email
   FROM Employee
)
SELECT name, email
FROM cte
WHERE c_name > 1 OR c_email > 1;

答案 2 :(得分:1)

最不复杂。一个快速而肮脏的解决方案。

SELECT 
    a.name, 
    a.email, count(*)
FROM
    employee a

INNER JOIN
    employee b on b.name = a.name or b.email = a.email
GROUP BY a.name, a.email
HAVING COUNT(*) > 1