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),',')
)
select col,count(*) as qty
from a2 group by col order by col desc
[解决办法]
declare @tb table(id int, tags nvarchar(100))
insert into @tb
select 1,N'英国,美国,意大利' union all
select 2,N'美国' union all
select 3,null union all
select 4,N'英国,意大利' union all
select 5,N'意大利' union all
select 6,N'中国'
declare @sql nvarchar(1000)
select @sql = ISNULL(@sql,'') + isnull(tags,'null') + ',' from @tb
select @sql = STUFF(@sql,LEN(@sql),1,'')
select @sql = 'select col,count(*) from (select N''' + REPLACE(@sql,',',''' as col union all select N''')+ ''') t group by col order by count(*) desc'
exec(@sql)