日期:2014-05-18 浏览次数:20596 次
select A , (select count(1) from test where B=0 and t.A = test.A) as B0 , (select count(1) from test where B=1 and t.A = test.A) as B1 from test t group by A
------解决方案--------------------
declare @t table ( A char(1),B tinyint)
insert into @t
select 'a',0 union all
select 'a',0 union all
select 'a',1 union all
select 'b',0 union all
select 'b',1 union all
select 'b',1 union all
select 'b',1
select A,SUM(case when B = 0 THEN 1 ELSE 0 END ) AS B0,
SUM(case when B = 1 THEN 1 ELSE 0 END ) AS B1
from @t group by A
-----------------------------------------
(7 行受影响)
A B0 B1
---- ----------- -----------
a 2 1
b 1 3
(2 行受影响)