请教一下,如何写做下面较复杂的统计汇总SQL语句?
我有一表Table1 字段名为: A B C D E
字段值为: t 1 0 0 1
h 0 1 0 1
t 0 0 1 0
h 1 0 0 1
h 1 1 1 0
... ... ... ... ...
我想要的结果为: A字段的记录条数 B字段值为1的条数 C字段值为0的条数
t 2 1 2
h 3 2 1
... ... ... ...
用一条SQL语句统计.
请高手帮帮忙.小弟对SQL语言掌握不好.谢谢了!
[解决办法]
declare @Table1 table(A char(1),B int,C int,D int,E int)
insert @Table1
select 't ',1,0,0,1
union all
select 'h ',0,1,0,1
union all
select 't ',0,0,1,0
union all
select 'h ',1,0,0,1
union all
select 'h ',1,1,1,0
select count(*) a,sum(b) b,sum(c-1)*-1 c from @Table1
group by a
-----------------------------------------------
(所影响的行数为 5 行)
a b c
----------- ----------- -----------
3 2 1
2 1 2
(所影响的行数为 2 行)
[解决办法]
一种简单可行的办法,我已经测试过了,保证没有问题
select a= 't ',b=1,c=0,d=0,e=1 into #table
insert into #table values( 'h ',0,1,0,1)
insert into #table values( 't ',0,0,1,0)
insert into #table values( 'h ',1,0,0,0)
insert into #table values( 'h ',1,1,1,1)
select a,count(a) a_count,sum(b) b_1,count(c)-sum(c) c_0 from #table group by a
drop table #table
a a_count b_1 c_0
----------------------------
t 2 1 2
h 3 2 1
(所影响的行数为 1 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
(所影响的行数为 2 行)