2

I have a test table to demonstrate the issue:

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

I need to output something like this:

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

Attempted Queries

I looked for several answers on SO and I wasn't able to find exactly what I need. Here is the first related question and the queries I tried: Counting the rows of multiple distinct columns

Query:

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

Results in:

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

Query:

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

Results in:

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

I also tried the answers in this question: How can I count distinct multiple fields without repeating the query?

Query:

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

Result:

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

As you can tell, I'm having a hard time figuring out how to do this... I would think it should be relatively simple, but I'm missing something.

4

2 回答 2

3

Unless I'm mistaken, this would work:

SELECT NetworkId, CountryCode, COUNT(Id) as DistCount
FROM TestTable
GROUP BY NetworkId, CountryCode
于 2012-12-11T00:04:51.027 回答
3

If Id is unique and not null within TestTable (which it will be if it is the primary key), then this query will return the result set you specified:

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

However, if the Id column is not unique, and what you want is a count of distinct non-null Id values within each group, you can add the DISTINCT keyword:

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

Given your sample data, both queries will return the same result. There will be a difference only if you have duplicate Id values within a group.

于 2012-12-11T00:05:17.440 回答