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

sql表中有一分号列,如何统计这列中没行分号的个数
sql表中有一分号列,如何统计这列中没行分号的个数
如:
1  a;b;c
2  a;b
3  cc;dd;33
查询结果
名字 个数
1    3
2    2
3    3

------解决方案--------------------
;with cte(id,value) as
(
select 1,'a;b;c'
union all select 2,'a;b'
union all select 3,'cc;dd;33'
)
select id,LEN(value)-LEN(replace(value,';',''))+1 as result
from cte

/*
id result
1 3
2 2
3 3
*/

------解决方案--------------------
修改一点,如果存在空字符串,则为0

;with cte(id,value) as
(
select 1,'a;b;c'
union all select 2,'a;b'
union all select 3,'cc;dd;33'
union all select 4,'xx'
union all select 5,''
)
select id,LEN(value)-LEN(replace(value,';',''))+case when LEN(value)>0 then 1 else 0 end as result
from cte

/*
id result
1 3
2 2
3 3
4 1
5 0
*/

------解决方案--------------------



declare @t table(id int ,value varchar(100)) 

insert into @t
select 1,'a;b;c'
union all select 2,'a;b'
union all select 3,'cc;dd;33'
union all select 4,''


select id as 名字,
       len(value) - len(replace(value,';','')) as 个数
from @t t
/*
名字 个数
1 2
2 1
3 2
4 0
*/

------解决方案--------------------

create table wg
(x int,y varchar(10))

insert into wg
 select 1,'a;b;c' union all
 select 2,'a;b' union all
 select 3,'cc;dd;33'


select a.x '名字',
       count(substring(a.y,b.number,charindex(';',a.y+';',b.number)-b.number)) '个数'
 from wg a
 inner join master.dbo.spt_values b
 on b.type='P' and b.number between 1 and len(a.y)
 and substring(';'+a.y,b.number,1)=';'
 group by a.x

/*
名字          个数
----------- -----------
1           3
2           2
3           3

(3 row(s) affected)
*/