33

I am new to sql so please be kind.

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

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

Win Coder
  • 6,628
  • 11
  • 54
  • 81

4 Answers4

44
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 *

SELECT e1.* FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;
yceruto
  • 9,230
  • 5
  • 38
  • 65
agusluc
  • 1,445
  • 2
  • 16
  • 24
37

How about

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

SQL Fiddle DEMO

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
1

You can do this without a 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

Hart CO
  • 34,064
  • 6
  • 48
  • 63
-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

Roman Pekar
  • 107,110
  • 28
  • 195
  • 197