SQL 统计 编号 在表中出现的次数,求大神。
PersonID AttnIDs
---------------- --------
18 13 10
15 16 15
15 9
PersonID为int型,AttnIDs为varchar型.统计数字在这张表中出现的次数.(如第二行数据中出现2个15,那么只算其出现一次)
做出最后结果为
ID 次数
---------------- --------
18 1
13 1
10 1
15 2
16 1
9 1
求大神解决.或者给我一个思路。
[解决办法]
上面那个忘了过滤掉为空的,
- SQL code
if object_id('test') is not null drop table testgocreate table test(PersonID int,AttnIDs varchar(20))goinsert into testselect 18,'13 10' union allselect 15,'16 15' union allselect 15,'9'godeclare @xml xml,@str varchar(max) select @str=isnull(@str,'')+'<x>'+convert(varchar(5),PersonID)+'</x><x>'+replace(replace(AttnIDs,convert(varchar(5),PersonID),''),' ','</x><x>')+'</x>' from testselect @xml=convert(xml,@str);with cte as( select N.v.value('.','varchar(10)') ID from @xml.nodes('/x') N(v))select ID,count(ID) cnt from ctewhere ID<>''group by ID/*(3 行受影响)ID cnt---------- -----------10 113 115 216 118 19 1(6 行受影响)*/