使用group by和self join查找重复项

时间:2016-10-21 04:54:12

标签: sql postgresql

我有一个我试图查询的表,如下所示:

t_documents
id
user_id
submitted_date
text
status

用户可以在文档表中拥有多个文档,并且可以多次提交相同的文本。我想要一种方法来查看每个用户提交了多少重复提交。所以对于前:

VALUES (1, 1234, 2016-07-05, "this is a test", 3)
VALUES (2, 1234, 2016-07-06, "this is a test", 3)
VALUES (3, 5678, 2016-07-07, "this is another test", 3)
VALUES (4, 5678, 2016-07-08, "this is another test", 3)

对于上面的数据集,我想要一个结果,说明给我一个用户1234的记录,重复的文本和重复文本的提交次数。我尝试过以下方法:

select oring.user_id, orig.text, COUNT(1) as dups
from t_documents orig
join t_documents another
on orig.user_id = another.user_id
and orig.text = another.text
group by user_id

以上是超级粗糙的,不起作用。任何人都可以建议如何做我想要的?我感兴趣的另一个问题是,所有用户总共有多少重复条目?

1 个答案:

答案 0 :(得分:3)

我不确定你在这里需要自我加入。用户ID和文本列上的简单GROUP BY就足够了:

SELECT user_id, COUNT(*) AS dup_count
FROM t_documents
GROUP BY user_id, text

我在此假设您在确定文本是否重复时关心过帐日期。

修改

如果您想在所有用户中找到重复的总数,那么您可以尝试以下查询:

SELECT SUM(t.dup_count)
FROM
(
    SELECT user_id, COUNT(*) - COUNT(DISTINCT text) AS dup_count
    FROM t_documents
    GROUP BY user_id
) t