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
Counting without duplicates
提问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 DISTINCT
inside COUNT()
so it will only count unique values.
这里的关键是使用DISTINCT
insideCOUNT()
所以它只会计算唯一值。
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 distinct
key 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