日期:2014-05-17  浏览次数:20750 次

sql 数据库表,统计字符串出现的次数


表:info

id         tags
1          英国,美国,意大利
2          美国
3          NULL
4          英国,意大利
5          意大利
6          中国
...        ...
需求如下:
查询这张表,统计其以逗号分割的字符串,在tags列中出现的次数.按照倒序排列输出.

SQL 数据库 ASP.NET

------解决方案--------------------
--先運行以下命令創建自定義函數:
create   function   f_split(@c   varchar(2000),@split   varchar(2))   
returns   @t   table(col   varchar(20))   
as   
    begin   
    
      while(charindex(@split,@c)<>0)   
        begin   
          insert   @t(col)   values   (substring(@c,1,charindex(@split,@c)-1))   
          set   @c   =   stuff(@c,1,charindex(@split,@c),'')   
        end   
      insert   @t(col)   values   (@c)   
      return   
    end   
go   

--再運行以下命令取結果:
with a1 as
(
SELECT top 1 tags=stuff
(
(select ','+RTRIM(tags) as [text()]
from gxx_sites b where 1=1
for xml path('')
),1,1,'') FROM gxx_sites a 
)
,a2 as
(
select * from  dbo.f_split((select tags from a1),',')