我有一个我正在尝试查询的表,它看起来像这样:
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
以上是 super 粗略的,不起作用。任何人都可以建议如何做我想做的事吗?我感兴趣的另一个查询是,所有用户总共有多少重复条目?
最佳答案
我不确定您是否需要在此处自行加入。用户 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
关于sql - 使用 group by 和 self join 查找重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40168679/