Sql 在以下情况下使用大小写创建多个计数列

Sql 在以下情况下使用大小写创建多个计数列,sql,sql-server,Sql,Sql Server,我必须用不同的标准对计算同一列的语句进行分类。我遇到的问题是,第一个case在Test2列中创建了一个null条目,但随后在第二个case语句中对其进行计数,并将test1列保留为null。我想有两个计数并排,而不是创建一个重复的行 select m.no, Case when itemtype = 'S' THEN count(ITEMKEY) end as Test1, case when ItemType='C' THEN count(ITEMKEY) END as Test2 fro

我必须用不同的标准对计算同一列的语句进行分类。我遇到的问题是,第一个case在Test2列中创建了一个null条目,但随后在第二个case语句中对其进行计数,并将test1列保留为null。我想有两个计数并排,而不是创建一个重复的行

select m.no,  
Case when itemtype = 'S' THEN count(ITEMKEY) end as Test1,
case when ItemType='C' THEN count(ITEMKEY) END as Test2
from test m

我很确定你想要条件聚合。
case
表达式是聚合函数的参数:

select m.no, 
       sum(case when itemtype = 'S' then 1 else 0 end) as test1,
       sum(case when itemtype = 'C' then 1 else 0 end) as test2
from test m
group by m.no;

这假设
itemKey
从来都不是
null
,因此
count()
只是在计算行数。

我很确定您需要条件聚合。
case
表达式是聚合函数的参数:

select m.no, 
       sum(case when itemtype = 'S' then 1 else 0 end) as test1,
       sum(case when itemtype = 'C' then 1 else 0 end) as test2
from test m
group by m.no;

这假设
itemKey
从来都不是
null
,因此
count()
只是在计算行数。

以下查询可以显示具有itemKey计数的Itemtype“S”或“C”的记录。如果itemkey为空,则显示0个itemkey计数

select m.no,  
Case when isnull( m.itemtype = 'S',0) THEN (select count(a.ITEMKEY) from test a where  a.itemtype = 'S' ) else 0 end as Test1,
case when isnull( m.itemtype='C',0) THEN (select count(b.ITEMKEY) from test b where  b.itemtype = 'C') else 0 END as Test2
from test m

以下查询可以显示Itemtype为“S”或“C”且itemkey计数为的记录。如果itemkey为空,则显示0个itemkey计数

select m.no,  
Case when isnull( m.itemtype = 'S',0) THEN (select count(a.ITEMKEY) from test a where  a.itemtype = 'S' ) else 0 end as Test1,
case when isnull( m.itemtype='C',0) THEN (select count(b.ITEMKEY) from test b where  b.itemtype = 'C') else 0 END as Test2
from test m