日期:2014-05-19  浏览次数:20424 次

再问一个分类统计的
表结构:
B  N  NU
字段值: 
_______
B1 N1 1
B1 N1 2
B1 N2 3
B1 N2 4
B1 N3 5
B1 N4 6

B2 N1 2
B2 N1 3
B2 N2 2
B2 N2 3
B2 N3 2
B2 N4 3
B2 N4 4
 .  . .
 .  . .
 .  . .
想输出:
B1 N1       3
       N2       7
        N3    5
          N4         6
B2       N1    5
       N2 5
       N3 2
       N4 7


想输出:

------解决方案--------------------
--创建测试环境
create table t(B varchar(10),N varchar(10),NU int)

--插入测试数据
insert t(B,N,NU)
select 'B1 ', 'N1 ', '1 ' union all
select 'B1 ', 'N1 ', '2 ' union all
select 'B1 ', 'N2 ', '3 ' union all
select 'B1 ', 'N2 ', '4 ' union all
select 'B1 ', 'N3 ', '5 ' union all
select 'B1 ', 'N4 ', '6 ' union all
select 'B2 ', 'N1 ', '2 ' union all
select 'B2 ', 'N1 ', '3 ' union all
select 'B2 ', 'N2 ', '2 ' union all
select 'B2 ', 'N2 ', '3 ' union all
select 'B2 ', 'N3 ', '2 ' union all
select 'B2 ', 'N4 ', '3 ' union all
select 'B2 ', 'N4 ', '4 '

--求解过程
select B,N,sum(NU) as NU from t
group by B,N
order by B,N

--删除测试环境
drop table t

/*--测试结果

*/
B N NU
---------- ---------- -----------
B1 N1 3
B1 N2 7
B1 N3 5
B1 N4 6
B2 N1 5
B2 N2 5
B2 N3 2
B2 N4 7

(所影响的行数为 8 行)
/*
------解决方案--------------------
create table t (B varchar(5), N varchar(5), NU int)

insert into t
select 'B1 ', 'N1 ', '1 '
union select 'B1 ', 'N1 ', '2 '
union select 'B1 ', 'N2 ', '3 '
union select 'B1 ', 'N2 ', '4 '
union select 'B1 ', 'N3 ', '5 '
union select 'B1 ', 'N4 ', '6 '
union select 'B2 ', 'N1 ', '2 '
union select 'B2 ', 'N1 ', '3 '
union select 'B2 ', 'N2 ', '2 '
union select 'B2 ', 'N2 ', '3 '
union select 'B2 ', 'N3 ', '2 '
union select 'B2 ', 'N4 ', '3 '
union select 'B2 ', 'N4 ', '4 '

SELECT B, N, SUM(NU) FROM T GROUP BY B, N
ORDER BY B, N

------解决方案--------------------
if object_id( 'pubs..tb ') is not null
drop table tb
go

create table tb(B varchar(10),N varchar(10),BU int)
insert into tb(B,N,BU) values( 'B1 ', 'N1 ',1)
insert into tb(B,N,BU) values( 'B1 ', 'N1 ',2)
insert into tb(B,N,BU) values( 'B1 ', 'N2 ',3)
insert into tb(B,N,BU) values( 'B1 ', 'N2 ',4)
insert into tb(B,N,BU) values( 'B1 ', &