Найти количество повторяющихся подряд символов в строке через запрос SQL
Необходимо создать запрос в MS SQL, который будет выводить в колонку (Count) количество повторяющихся подряд символов (в моем случае цифр) из колонки (String) таблицы. Можно ли это сделать без использования внешних функций? Пример результата:
| String | Count |
|---|---|
| 12344444567 | 5 |
| 9584028176 | 1 |
| 99 | 2 |
Для обработки нулей использовал следующий код:
select String, case
when (cast(String as decimal(28,0)) <> 0 and ((cast(cast(String as numeric(28,2))as bigint))%1000000000) = 0) then 9
when (cast(String as decimal(28,0)) <> 0 and ((cast(cast(String as numeric(28,2))as bigint))%100000000) = 0) then 8
when (cast(String as decimal(28,0)) <> 0 and ((cast(cast(String as numeric(28,2))as bigint))%10000000) = 0) then 7
when (cast(String as decimal(28,0)) <> 0 and ((cast(cast(String as numeric(28,2))as bigint))%1000000) = 0) then 6
when (cast(String as decimal(28,0)) <> 0 and ((cast(cast(String as numeric(28,2))as bigint))%100000) = 0) then 5
when (cast(String as decimal(28,0)) <> 0 and ((cast(cast(String as numeric(28,2))as bigint))%10000) = 0) then 4
when (cast(String as decimal(28,0)) <> 0 and ((cast(cast(String as numeric(28,2))as bigint))%1000) = 0) then 3
when (cast(String as decimal(28,0)) <> 0 and ((cast(cast(String as numeric(28,2))as bigint))%100) = 0) then 2
end Count
from Table p
Обработать остальные цифры затрудняюсь.
Ответы (1 шт):
Автор решения: ValNik
→ Ссылка
Посмотрите, как пример разборки-подчстета символов
with nn as(select 1 i union all select i+1 from nn where i<20) -- серия чисел от 1 до..
-- исходные данные
,data as(select * from ( values
(1,'12344455')
,(2,'123333433355aaaAA')
)t(id,sv)
)
-- разборка строки на символы
,syms as(
select id,i,substring(sv,i,1)s1
,sv
from data d
inner join nn on i<=len(sv)
)
-- проставим признак текущий символ отличается от предыдущего - начало группы
,grs as(
select *
,case when s1<>lag(s1,1,'')over(partition by id order by i) then 1 else 0 end ns
from syms
)
-- пронумеруем группы последовательностей
,grn as(
select *
,sum(ns)over(partition by id order by i) grn
from grs
)
-- подсчитаем число символов каждой группе
,seq as(
select id,min(s1)s1,count(*)q,min(i) i
from grn
group by id,grn
)
select *
from seq
order by id,i
;
Результат разборки-группировки
| id | s1 | q | i |
|---|---|---|---|
| 1 | 1 | 1 | 1 |
| 1 | 2 | 1 | 2 |
| 1 | 3 | 1 | 3 |
| 1 | 4 | 3 | 4 |
| 1 | 5 | 2 | 7 |
| 2 | 1 | 1 | 1 |
| 2 | 2 | 1 | 2 |
| 2 | 3 | 4 | 3 |
| 2 | 4 | 1 | 7 |
| 2 | 3 | 3 | 8 |
| 2 | 5 | 2 | 11 |
| 2 | a | 5 | 13 |