求SQL语句,急~~
表结构:
name type category
------------------------
N1 T1 C1
N2 T1 C2
N3 T2 C1
N4 T3 C3
N5 T2 C4
N6 T3 C5
N1 T1 C1
统计结果:
Category name T1 T2 T3
----------------------------
C1 N1 2 0 0
C1 N3 0 1 0
C2 N2 1 0 0
C3 N4 0 0 1
C4 N5 0 1 0
C5 N6 0 0 1
请大家帮忙看看
------解决方案--------------------select Category, name,
sum(case when type= 'T1 ' then 1 else 0 end ) as T1,
sum(case when type= 'T2 ' then 1 else 0 end ) as T2,
sum(case when type= 'T3 ' then 1 else 0 end ) as T3
from tblname
group by Category , name
------解决方案--------------------樓上.
------解决方案--------------------如果T1 T2 T3 T4...不固定就不好弄了
------解决方案--------------------drop table #test
create table #test(name nvarchar(20),type nvarchar(20),category nvarchar(20))
select * from #test
insert into #test(name,type,category) values ( 'n1 ', 't1 ', 'c1 ');
insert into #test(name,type,category) values ( 'n2 ', 't1 ', 'c2 ');
insert into #test(name,type,category) values ( 'n3 ', 't2 ', 'c1 ');
insert into #test(name,type,category) values ( 'n4 ', 't3 ', 'c3 ');
insert into #test(name,type,category) values ( 'n5 ', 't2 ', 'c4 ');
insert into #test(name,type,category) values ( 'n6 ', 't3 ', 'c5 ');
insert into #test(name,type,category) values ( 'n1 ', 't1 ', 'c1 ');
select category,name,sum(case when type= 't1 ' then 1 else 0 end),sum(case when type= 't2 ' then 1 else 0 end),sum(case when type= 't3 ' then 1 else 0 end) from #test group by name,category
------解决方案--------------------mark
------解决方案--------------------