作业帮 > 综合 > 作业

用SQL计算同一个字符(汉字、字母、数字、表情、符号)连续重复出现的次数

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/04/29 05:44:39
用SQL计算同一个字符(汉字、字母、数字、表情、符号)连续重复出现的次数
如:aaaa%%%vfahg%&&&
可以看出a连续重复4次,%连续重复3次,&连续重复3次
SQL Server可以使用如下查询,其他数据库要做相应修改:
declare @s nvarchar(4000), @i int, @len int, @v nvarchar(10)
set @s = 'aaaa%%%vfahg%&&&'
declare @tb table (txt nvarchar(10), cnt int)
select @i = 0, @len = len(@s)
while @i < @len
begin
 set @v = substring(@s, @i + 1, 1)
 update @tb
 set cnt = cnt + 1
 where txt = @v
 
 if @@rowcount < 1
 begin
  insert into @tb (txt, cnt)
  select @v, 1
 end
 set @i = @i + 1
end
select * from @tb
再问: 是连续重复呢。这样的话%应该只有3次。请问这个怎么写啊?
再答: 那就加入判断,但是间隔开来的连续(指类似%%%faffd%%,这种情况是合并起来计数的),SQL如下:declare @s nvarchar(4000), @i int, @len int, @v nvarchar(10), @t nvarchar(10), @cc int
select @s = 'aaaa%%%vfahg%&&&', @t = ''
declare @tb table (txt nvarchar(10), cnt int)
select @i = 0, @len = len(@s)
while @i < @len
begin
 set @v = substring(@s, @i + 1, 1)
 if @t = @v   -- 与之前值相同,视为连续
 begin
  update @tb
  set cnt = cnt + (case when @cc = 1 then 2 else 1 end)
  where txt = @v
   
  if @@rowcount < 1
  begin
   insert into @tb (txt, cnt)
   select @v, 2
  end
 
     set @cc = @cc + 1
 end
 else
 begin
     select @t = @v, @cc = 1
 end
 set @i = @i + 1
end
select * from @tb