日期:2014-05-16  浏览次数:20537 次

【求助】sql分割字符串并分组统计问题
现有如图所示的数据表,如何用SQL语句由第一个表得到第二个表的内容

表一

表二
------解决方案--------------------
--drop table t

create table t(id int,name varchar(10),title varchar(20))

insert into t
select 1,'aaa,bbb','test1' union all
select 1,'aaa,bbb,cc','test2' union all
select 1,'bbb','test3'
go


select COUNT(*) sum,name
from
(
select id,
       SUBSTRING(t.name, number ,CHARINDEX(',',t.name+',',number)-number) name
from t,master..spt_values s
where s.number >=1
and s.type = 'P'
and SUBSTRING(','+t.name,s.number,1) = ','
)t
group by name
/*
sum name
2 aaa
3 bbb
1 cc
*/