简体   繁体   English

PostgreSQL在ID为ID的列中找到重复项

[英]postgresql find duplicates in column with ID

For instance, I have a table say "Name" with duplicate records in it: 例如,我有一个说“名称”的表,其中有重复的记录:

Id    |  Firstname
--------------------
1     |  John
2     |  John
3     |  Marc
4     |  Jammie
5     |  John
6     |  Marc

How can I fetch duplicate records and display them with their receptive primary key ID? 如何获取重复的记录并显示其接收主键ID?

Use Count()Over() window aggregate function 使用Count()Over()窗口聚合函数

Select * from
(
select Id, Firstname, count(1)over(partition by Firstname) as Cnt
from yourtable
)a
Where Cnt > 1
SELECT t.*
FROM t
INNER JOIN
(SELECT firstname
 FROM t
 GROUP BY firstname
 HAVING COUNT(*) > 1) sub
ON t.firstname = sub.firstname

A sub-query would do the trick. 子查询可以解决问题。 Select the first names that are found more than once your table, t. 选择不止一次在表中找到的名字t。 Then join these names back to the main table to pull in the primary key. 然后将这些名称重新加入主表以拉入主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM