我有一个users
表,在employee_id
列中有重复的值。我需要列出所有有重复员工ID的行,以及他们的名字。我需要查看所有具有重复employee_id
的用户,以便消除哪些值有效的冲突。
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
我看到类似的问题,但我仍然无法得到正确的语法,我需要。下面我只得到一个事件。我需要以上所有重复的发生。
SELECT employee_id, MAX(name)
FROM users
GROUP BY employee_id
HAVING COUNT(employee_id) > 1;
最佳答案
您可以使用windowedCOUNT
:
SELECT sub.name, sub.employee_id
FROM (SELECT *, COUNT(*) OVER(PARTITION BY employee_id) AS c
FROM users) AS sub
WHERE c > 1;
LiveDemo
或简单的:
SELECT *
FROM users
WHERE employee_id IN (SELECT employee_id
FROM users
GROUP BY employee_id
HAVING COUNT(employee_id) > 1);
IN
或相关子查询:
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;
LiveDemo2