簡體   English   中英

Count Distinct 未按預期工作,output 等於 count

[英]Count Distinct not working as expected, output is equal to count

我有一張表,我正在嘗試計算每個組的不同成員數量。 我知道有基於計數(不同 *)function 的重復項。 但是當我嘗試將它們分組並分別計數時,它並沒有吐出我期望的數字。

select count(distinct memberid), count(*) 
from dbo.condition c 

output:

數數 數數
303,781 348,722
select groupid, count(*), count(distinct memberid) 
from dbo.condition c 
group by groupid

output:

群號 數數 數數
2 19,984 19,984
3 25,689 25,689
5 14,400 14,400
24 56,058 56,058
25 200,106 200,106
29 27,847 27,847
30 1,370 1,370
31 3,268 3,268

第二個查詢中的數字等於它們不應該等於的時間。 有誰知道我做錯了什么? 我需要第三列等於 303,781 而不是 348,722。

謝謝!

您的第二個查詢沒有問題。 由於您在“ groupid ”字段上進行聚合,因此您得到的 output 會告訴您“ memberid ”值的相同 groupid 內沒有重復項(基本上計數值等於單獨計數)。

另一方面,在第一個查詢中,聚合發生時沒有任何分區,其 output 提示在不同的“ groupid ”值之間存在重復值。

冒昧地添加了一個可以證實您的答案的示例:

create table aa (groupid int not null, memberid int not null );

insert into aa (groupid, memberid) 
values 
(1, 1), (1, 2), (1, 3), (2, 1), (3, 1), (3, 2), (3, 3), (4, 1), (4, 2), (4, 3), (4, 5), (5, 3)

select groupid, count(*), count(distinct memberid) 
from aa group by groupid;

select count(*), count(distinct memberid) 
from aa

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM