I have a data in Microsoft SQL server with the following format:
id1 id2 month quantA quantB
1 10 1 5 15
1 10 1 10 20
1 10 2 5 10
1 10 2 10 NULL
1 11 1 NULL NULL
1 11 2 5 NULL
1 11 2 10 5
2 10 1 10 20
2 10 1 5 NULL
2 11 2 NULL NULL
I need to construct a table grouped by id1 and month with the following columns:
id1
month
var1 = count how many *distinct* id2 by month and id1 for which quantA!=Null
var2 = count how many *distinct* id2 by month and id1 for which quantB!=Null
You can construct the query basically how you have written it:
COUNT DISTINCTignores NULLs when doing the count.