如何找到重复项(正确方法)?

How to find duplicates (correct way)?

我正在使用 Snowflake 数据库和 运行 这个查询来查找总计数、不同记录的数量和差异:

select 
    (select count(*) from mytable) as total_count, 
    (select count(*) from (select distinct * from mytable)) as distinct_count,
    (select count(*) from mytable) - (select count(*) from (select distinct * from mytable)) as duplicate_count
from mytable limit 1;

结果:

1,759,867
1,738,924
20,943 (duplicate_count)

但是当尝试使用其他方法时(将所有列分组并找到计数 > 1 的位置):

select count(*) from (
SELECT 
    a, b, c, d, e,
    COUNT(*)
FROM 
    mytable
GROUP BY 
    a, b, c, d, e
HAVING 
    COUNT(*) > 1
)

我得到 5,436.

为什么重复次数不同? (20,943 对比 5,436)

谢谢。

好的。让我们从一个简单的例子开始:

create table #test
(a int, b int, c int, d int, e int)

insert into #test values (1,2,3,4,5)
insert into #test values (1,2,3,4,5)
insert into #test values (1,2,3,4,5)
insert into #test values (1,2,3,4,5)
insert into #test values (1,2,3,4,5)
insert into #test values (5,4,3,2,1)
insert into #test values (5,4,3,2,1)
insert into #test values (1,1,1,1,1)

并尝试您的子查询以了解您将得到什么:

SELECT 
    a, b, c, d, e,
    COUNT(*)
FROM 
    #test
GROUP BY 
    a, b, c, d, e
HAVING 
    COUNT(*) > 1

想一想...

当当当当~

a   b   c   d   e   (No column name)
1   2   3   4   5   5
5   4   3   2   1   2

它只会 return 两行,因为你使用了 'group by'。但它仍然计算每个 a、b、c、d、e 组合的重复数字。

如果你想要重复的总数,试试这个:

select sum(sub_count) from (
SELECT 
    a, b, c, d, e,
    COUNT(*) - 1 as sub_count
FROM 
    #test
GROUP BY 
    a, b, c, d, e
HAVING 
    COUNT(*) > 1)a

如果我正确理解您的原始查询,您需要在这种情况下减一。如果我错了请纠正我。