路过请进,求一SQL语句,在线等!
表table1如下:(没有主键,因为实际表中字段较多,不存在两行数据完全相同的,现用dif字段以示区别)
name ta dif
a 1 1
b 2 2
c 3 3
a 1 4
a 2 5
b 3 6
b 2 7
我想通过查询行到的结果:
name ta=1 ta=2 ta=3
a 2 1 0
b 0 2 1
c 0 0 1
也就是想得到这个表中对应name的各个ta值分别为1,2,3的次数.
谢谢
------解决方案--------------------有一表table1有很多字段,其中有如下两条
create table #t
(name varchar(10), col int)
insert into #t
select 'a ', 1 union all
select 'b ', 2 union all
select 'c ', 3 union all
select 'a ', 1 union all
select 'a ', 2 union all
select 'b ', 3
select distinct name, 'ta=1 '=(select count(*) from #t where a.name=name and col=1),
'ta=2 '=(select count(*) from #t where a.name=name and col=2),
'ta=3 '=(select count(*) from #t where a.name=name and col=3)
from #t a
--or
select name ,
sum(case when col=1 then 1 else 0 end) as 'ta=1 ',
sum(case when col=2 then 1 else 0 end) as 'ta=2 ',
sum(case when col=3 then 1 else 0 end) as 'ta=3 '
from #t
group by name
name ta=1 ta=2 ta=3
----------