当前位置: 代码迷 >> Sql Server >> sql分割字符串并分组统计有关问题
  详细解决方案

sql分割字符串并分组统计有关问题

热度:8   发布时间:2016-04-24 18:26:23.0
【求助】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
*/
  相关解决方案