-------------------------------------------------------------------------------------- --统计示例 --为统计处理专门做的序数表 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.keyword<b.keyword group 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 行)