# 分拆统计字符串

id??????????????????????? keywords
-----------------------------------------------------------
1????????????????????????? kw1;kw2;kw3
2????????????????????????? kw2;kw3
3????????????????????????? kw3;kw1;kw4

keywords?????? count
-------------------------
kw1????????????? 2
kw2????????????? 2
kw3????????????? 3
kw4????????????? 1

keywords???????????? count
----------------------------------
kw1;kw2??????????????? 1
kw1;kw3??????????????? 2
kw1;kw4??????????????? 1
kw2;kw3??????????????? 2
kw2;kw4??????????????? 0
kw3;kw4??????????????? 1

--------------------------------------------------------------------------------------

--统计示例

--为统计处理专门做的序数表
select top 1000 id=identity(int,1,1) into 序数表 from syscolumns a,syscolumns b
alter table 序数表 add constraint pk_id_序数表 primary key(id)
go

--示例数据
create table tbl1(id int,keywords nvarchar(1000))
insert tbl1 select 1,'kw1;kw2;kw3'
union? all? select 2,'kw2;kw3'
union? all? select 3,'kw3;kw1;kw4'
go

--第一种统计(计数)
select keyword=substring(a.keywords,b.id,charindex(';',a.keywords+';',b.id)-b.id)
?,[count]=count(distinct a.id)
from tbl1 a,序数表 b
where b.id<=len(a.keywords)
?and substring(';'+a.keywords,b.id,1)=';'
group by substring(a.keywords,b.id,charindex(';',a.keywords+';',b.id)-b.id)
go

--第二种统计(组合统计)
select keyword=substring(a.keywords,b.id,charindex(';',a.keywords+';',b.id)-b.id)
?,[count]=count(distinct a.id),a.id
into #t
from tbl1 a,序数表 b
where b.id<=len(a.keywords)
?and substring(';'+a.keywords,b.id,1)=';'
group by substring(a.keywords,b.id,charindex(';',a.keywords+';',b.id)-b.id),a.id

select keyword=a.keyword+';'+b.keyword,[count]=sum(case a.id when b.id then 1 else 0 end)
from #t a,#t b
where a.keywordgroup by a.keyword,b.keyword
order by keyword

drop table #t
go

--删除测试环境
drop table tbl1,序数表

/*--测试结果

--统计1
keyword??? count??
---------- --------
kw1??????? 2
kw2??????? 2
kw3??????? 3
kw4??????? 1

（所影响的行数为 4 行）

--统计2
keyword???????????????? count?????
----------------------- -----------
kw1;kw2???????????????? 1
kw1;kw3???????????????? 2
kw1;kw4???????????????? 1
kw2;kw3???????????????? 2
kw2;kw4???????????????? 0
kw3;kw4???????????????? 1

（所影响的行数为 6 行）
--*/

• 本文已收录于以下专栏：

举报原因： 您举报文章：分拆统计字符串 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)