2016-04-03 61 views
4

我有一個users表,它具有employee_id列中的重複值。我需要列出所有包含重複employee_id的行及其名稱。我需要查看所有重複使用employee_id的用戶,以便我可以解除哪些值有效。用於選擇一列中具有重複值的所有行的SQL

SELECT name,employee_id 
FROM users; 

name  | employee_id 
----------------------- 
jason  12345 
tom  34567 
jane  12345 
will  01020 
bill  12345 

我需要返回:

name  | employee_id 
------------------------- 
jason  12345 
jane   12345 
bill   12345 

我看到類似的問題,但我仍然不能得到正確的語法,我需要。隨着下面我只得到一個事件。我需要像上面那樣複製employee_id的所有發生。

SELECT employee_id, MAX(name) 
FROM users 
GROUP BY employee_id 
HAVING COUNT(employee_id) > 1; 

回答

8

你可以使用窗口COUNT

SELECT sub.name, sub.employee_id 
FROM (SELECT *, COUNT(*) OVER(PARTITION BY employee_id) AS c 
     FROM users) AS sub 
WHERE c > 1; 

LiveDemo

或簡單IN

SELECT * 
FROM users 
WHERE employee_id IN (SELECT employee_id 
         FROM users 
         GROUP BY employee_id 
         HAVING COUNT(employee_id) > 1); 

LiveDemo2

或相關子查詢:

SELECT name, employee_id 
FROM users u 
,LATERAL (SELECT COUNT(*) FROM users u2 WHERE u.employee_id = u2.employee_id) AS s(c) 
WHERE c > 1; 

SqlFiddleDemo

+1

這是偉大的,謝謝! – Jason

相關問題