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.
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:
However, if the
Idcolumn is not unique, and what you want is a count of distinct non-nullIdvalues within each group, you can add the DISTINCT keyword:Given your sample data, both queries will return the same result. There will be a difference only if you have duplicate
Idvalues within a group.