如何选择某些列中具有相同值的所有行

时间:2013-09-16 18:16:16

标签: sql sql-server inner-join

我是sql的新手所以请善待。

假设我必须显示所有具有相同电话号码的employee_id(两列都在同一个表中)

我如何继续处理此问题的内部联接或其他事情。

4 个答案:

答案 0 :(得分:30)

怎么样

SELECT *
FROM Employees
WHERE PhoneNumber IN (
    SELECT PhoneNumber
    FROM Employees
    GROUP BY PhoneNumber
    HAVING COUNT(Employee_ID) > 1
    )

SQL Fiddle DEMO

答案 1 :(得分:29)

SELECT * FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

更新:为了更好的性能和更快的查询,可以在*

之前添加e1
SELECT e1.* FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

答案 2 :(得分:1)

您可以在没有JOIN的情况下执行此操作:

SELECT *
FROM (SELECT *,COUNT(*) OVER(PARTITION BY phone_number) as Phone_CT
      FROM YourTable
      )sub
WHERE Phone_CT > 1
ORDER BY phone_number, employee_ids

演示:SQL Fiddle

答案 3 :(得分:-1)

select *
from Table1 as t1
where
    exists (
        select *
        from Table1 as t2 
        where t2.Phone = t1.Phone and t2.id <> t1.id
    )

<强> sql fiddle demo