SQL Query用于标识数字中的重复数字

时间:2014-01-08 12:10:56

标签: sql sql-server-2008

我一直在识别数字及其计数中的重复数字。

例如,查询应该能够识别

DataColumn ----------- Result1(repeated digit)---------------Result 2 (count of repeated digit)
----------------------------------------------------------------------------------------    
11112---------------------1--------------------------------------------4
222AA---------------------2--------------------------------------------3
0011---------------------0,1-------------------------------------------2,2
1111 ---------------------1--------------------------------------------4

请指导

2 个答案:

答案 0 :(得分:3)

SQL Fiddle

MS SQL Server 2008架构设置

create function [dbo].[CountRepeatedDigits]
(
  @Data varchar(10)
)
returns @returntable table 
(
  Result1 varchar(10),
  Result2 varchar(10)
)
as
begin
  declare @Result1 varchar(10) = ''
  declare @Result2 varchar(10) = ''
  declare @C1 varchar(1) = ''
  declare @C2 varchar(1) = ''
  declare @I int = 1
  declare @D varchar(11) = @Data + 'X'

  while len(@D) > 0
  begin
    set @C1 = left(@D, 1)

    if patindex('[0-9]', @C1) > 0 and
       patindex('[0-9]', @C2) > 0 and
       @C1 = @C2
    begin
      set @I += 1
    end
    else
    begin
      if @I > 1
      begin
        set @Result1 += ','
        set @Result1 += @C2

        set @Result2 += ','
        set @Result2 += cast(@I as varchar(11))
      end
      set @I = 1
    end

    set @C2 = @C1
    set @D = stuff(@D, 1, 1, '')
  end

  insert @returntable(Result1, Result2)
  select stuff(@Result1, 1, 1, ''), stuff(@Result2, 1, 1, '')

  return 
end

go

create table YourTable(DataColumn varchar(10))

insert into YourTable values 
('11112'),
('222AA'),
('0011'),
('1111'),
('1122334455')

查询1

select DataColumn,
       C.Result1,
       C.Result2
from YourTable as T
  cross apply dbo.CountRepeatedDigits(T.DataColumn) as C

<强> Results

| DATACOLUMN |   RESULT1 |   RESULT2 |
|------------|-----------|-----------|
|      11112 |         1 |         4 |
|      222AA |         2 |         3 |
|       0011 |       0,1 |       2,2 |
|       1111 |         1 |         4 |
| 1122334455 | 1,2,3,4,5 | 2,2,2,2,2 |

答案 1 :(得分:-1)

尝试这样的查询:

select length('1112') - length(regexp_replace('11112', '(1,2)', '')) from dual;