计算具有多个聚合列的行

时间:2012-12-11 00:00:38

标签: sql sql-server count distinct

我有一个测试表来证明这个问题:

Id  NetworkId   CountryCode
1       1           de
2       2           de
3       2           de
4       2           de
5       1           us
6       1           us
7       1           us
8       2           us

我需要输出这样的内容:

NetworkId   CountryCode    DistCount
    1           de              1
    2           de              3
    1           us              3
    2           us              1

尝试查询

我在SO上寻找了几个答案,但我无法找到我需要的答案。以下是我尝试的第一个相关问题和查询:Counting the rows of multiple distinct columns

查询:

SELECT NetworkId, CountryCode, COUNT(*) as DistCount
FROM (SELECT DISTINCT NetworkId, CountryCode FROM TestTable) AS FOO
GROUP BY NetworkId, CountryCode

结果:

NetworkId   CountryCode    DistCount
    1           de              1
    1           us              1
    2           de              1
    2           us              1

查询:

SELECT COUNT(DISTINCT(STR(NetworkId) + ',' + STR(CountryCode)))
FROM TestTable

结果:

Msg 8114, Level 16, State 5, Line 1
Error converting data type nvarchar to float.

我也在这个问题中尝试了答案:How can I count distinct multiple fields without repeating the query?

查询:

SELECT 
   NetworkId, 
   CountryCode,
   COUNT(*) OVER(PARTITION BY NetworkId, CountryCode) as DistCount
FROM TestTable
GROUP BY NetworkId, CountryCode

结果:

NetworkId   CountryCode    DistCount
    1           de              1
    1           us              1
    2           de              1
    2           us              1

正如你所知,我很难弄清楚如何做到这一点......我认为它应该相对简单,但我错过了一些东西。

2 个答案:

答案 0 :(得分:3)

除非我弄错了,否则这会有效:

SELECT NetworkId, CountryCode, COUNT(Id) as DistCount
FROM TestTable
GROUP BY NetworkId, CountryCode

答案 1 :(得分:3)

如果Id是唯一的且在TestTable中不为null(如果它是主键,则它将是空的),则此查询将返回您指定的结果集:

SELECT NetworkId, CountryCode, Count(1) AS DistCount
  FROM TestTable 
 GROUP BY NetworkId, CountryCode
 ORDER BY NetworkId, CountryCode

但是,如果Id列不是唯一的,并且您想要的是每个组中不同的非空Id值的计数,则可以添加DISTINCT关键字:

SELECT NetworkId, CountryCode, Count(DISTINCT Id) AS DistCount
  FROM TestTable 
 GROUP BY NetworkId, CountryCode
 ORDER BY NetworkId, CountryCode

根据您的示例数据,两个查询都将返回相同的结果。只有在组内有重复的Id值时才会有区别。