Joe*_*Joe 2 sql duplicates snowflake-cloud-data-platform
我正在使用 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;
Run Code Online (Sandbox Code Playgroud)
结果:
1,759,867
1,738,924
20,943 (duplicate_count)
Run Code Online (Sandbox Code Playgroud)
但是当尝试使用另一种方法时(将所有列分组并找到计数 > 1 的位置):
select count(*) from (
SELECT
a, b, c, d, e,
COUNT(*)
FROM
mytable
GROUP BY
a, b, c, d, e
HAVING
COUNT(*) > 1
)
Run Code Online (Sandbox Code Playgroud)
我明白了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)
Run Code Online (Sandbox Code Playgroud)
并尝试您的子查询以了解您会得到什么:
SELECT
a, b, c, d, e,
COUNT(*)
FROM
#test
GROUP BY
a, b, c, d, e
HAVING
COUNT(*) > 1
Run Code Online (Sandbox Code Playgroud)
想一会...
当当当当~
a b c d e (No column name)
1 2 3 4 5 5
5 4 3 2 1 2
Run Code Online (Sandbox Code Playgroud)
它只会返回两行,因为您使用了“分组依据”。但它仍然计算每个 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
Run Code Online (Sandbox Code Playgroud)
如果我正确理解您的原始查询,在这种情况下您需要减一。如果我错了,请纠正我。
| 归档时间: |
|
| 查看次数: |
4999 次 |
| 最近记录: |