Microsoft SQL具有多个不同的COUNT和WHERE子句

时间:2012-09-27 21:44:49

标签: sql

我在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  

我需要构建一个按id1month分组的表格,其中包含以下列:

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

1 个答案:

答案 0 :(得分: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。