簡體   English   中英

如何選擇某些列中具有相同值的所有行

[英]How to select all rows which have same value in some column

我是sql的新手,所以請善待。

假設我必須顯示所有具有相同電話號碼的employee_ids(兩列都在同一個表中)

我如何繼續這個問題內部聯接或什么。

怎么樣

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

SQL Fiddle DEMO

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;

你可以在沒有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小提琴

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

sql小提琴演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM