【问题标题】:How to find duplicates (correct way)?如何查找重复项(正确方法)?
【发布时间】:2019-05-21 22:37:20
【问题描述】:

我正在使用 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,9435,436

谢谢。

【问题讨论】:

    标签: sql duplicates snowflake-cloud-data-platform


    【解决方案1】:

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

    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
    

    它只会返回两行,因为您使用了“分组依据”。但它仍然计算每个 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
    

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

    【讨论】:

    • 太好了,谢谢.. 这是有道理的,因为起初我只为每个组分配了 1 个计数(但它可以超过 1 个相同的副本).. 现在数字匹配..
    • 有没有办法在不使用“临时”表的情况下从表中删除它们?
    • @Joe 1,如果您询问如何删除重复行。来这里:stackoverflow.com/questions/18390574/…。 2,我使用临时表进行测试。您可以在没有临时表的情况下删除。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多