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

时间:2022-09-27 07:56:47

I am new to sql so please be kind.

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

Assume i must display all the employee_ids which have the same phone number(Both columns are in the same table)

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

How am i to proceed on this problem inner join or something.

我如何继续这个问题内部联接或什么。

4 个解决方案

#1


30  

How about

怎么样

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

SQL Fiddle DEMO

#2


29  

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

Update : for better performance and faster query its good to add e1 before *

更新:为了更好的性能和更快的查询,在*之前添加e1的好处

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

#3


1  

You can do this without a JOIN:

您可以在没有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

Demo: SQL Fiddle

演示:SQL小提琴

#4


-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

sql小提琴演示

#1


30  

How about

怎么样

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

SQL Fiddle DEMO

#2


29  

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

Update : for better performance and faster query its good to add e1 before *

更新:为了更好的性能和更快的查询,在*之前添加e1的好处

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

#3


1  

You can do this without a JOIN:

您可以在没有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

Demo: SQL Fiddle

演示:SQL小提琴

#4


-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

sql小提琴演示