有一个表,表结构如下: a varchar(20); b varchar(20); c numeric(9); d numeric(9); 数据例如 a b c d A f 3.50 6.90 B f 8.33 5.64 C d 13.20 15.63 根据b字段汇总输出c-d大于0的记录数,c-d小于0的记录数,以及c不等于d的记录数,语句怎么写,谢谢!
declare @T table(a varchar(20),b varchar(20),c numeric(9),d numeric(9))
insert into @t select 'A','f',3.50,6.90
union all select 'B','f',8.33,5.64
union all select 'C','d',13.20,15.63
select b,
[c-d>0]=sum(case when c-d>0 then 1 else 0 end),
[c-d<0]=sum(case when c-d<0 then 1 else 0 end),
[c<>d]=sum(case when c<>d then 1 else 0 end)
from @t
group by b
declare @T table(a varchar(20),b varchar(20),c numeric(9),d numeric(9))
insert into @t select 'A','f',3.50,6.90
union all select 'B','f',8.33,5.64
union all select 'C','d',13.20,15.63
select [c-d>0]=sum(case when c-d>0 then 1 else 0 end),
[c-d<0]=sum(case when c-d<0 then 1 else 0 end),
[c<>d]=sum(case when c<>d then 1 else 0 end)
from @t