1

我在 Microsoft SQL Server 中有一个数据,格式如下:

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  

我需要构建一个按以下列分组id1的表:month

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
4

1 回答 1

2

您可以基本上按照您的编写方式构建查询:

select id1, month,
       count(distinct case when quantA is not null then id2 end) as var1,
       count(distinct case when quantB is not null then id2 end) as var2
from t
group by id1, month

COUNT DISTINCT计数时忽略 NULL。

于 2012-09-27T21:58:06.833 回答