SQL 无重复计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16133947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:56:02  来源:igfitidea点击:

Counting without duplicates

sql

提问by Marc

I have a table such as the following

我有一张如下表

 FK_OrgId , FK_UserId
 3 , 74
 1 , 74
 1 , 74
 3 , 4
 4 , 5
 1 , 5

I'm trying to count FK_OrgId but I have to eliminate duplicates. So, I want a result like

我正在尝试计算 FK_OrgId 但我必须消除重复项。所以,我想要一个结果

 FK_OrgId, count
 3 , 2
 1 , 2
 4 , 1

Any suggestions?

有什么建议?

回答by John Woo

The key here is to use DISTINCTinside COUNT()so it will only count unique values.

这里的关键是使用DISTINCTinsideCOUNT()所以它只会计算唯一值。

SELECT  FK_OrgId, COUNT(DISTINCT FK_UserId)
FROM    TableName
GROUP   BY FK_OrgId

OUTPUT

输出

╔══════════╦════════════╗
║ FK_ORGID ║ TOTALCOUNT ║
╠══════════╬════════════╣
║        1 ║          2 ║
║        3 ║          2 ║
║        4 ║          1 ║
╚══════════╩════════════╝

回答by Stephane Rolland

you should use distinctkey word so as to avoid dupplicates

你应该使用distinct关键字以避免重复

select  t.FK_OrgId, count(distinct t.FK_UserId)
from    TableName as t
group by t.FK_OrgId