如何查找字符在字符串中出现的连续次数

时间:2019-04-17 16:45:51

标签: sql sql-server count google-bigquery standard-sql

我有一个字符串11111122111131111111

我想创建一个连续显示1的次数的数组,即前6个字符为1s->两个2's->四个1's->一个3->七个1s

所以我想要的输出是[6,4,7]

我知道如何查找字符出现在字符串中的次数,但是如何查找字符在连续模式中出现的次数。

3 个答案:

答案 0 :(得分:1)

以下示例适用于BigQuery标准SQL

#standardSQL
WITH `project.dataset.table` AS (
  SELECT '11111122111131111111' line
)
SELECT line, ARRAY(SELECT LENGTH(e) FROM UNNEST(REGEXP_EXTRACT_ALL(line, r'1+')) e) result
FROM `project.dataset.table`   

有结果

[
  {
    "line": "11111122111131111111",
    "result": [
      "6",
      "4",
      "7"
    ]
  }
]

答案 1 :(得分:1)

对实际的RDBMS有点不清楚

在这里,我们使用临时的计数表(任何大小合适的表都可以)。然后,我们应用标准的差距和岛屿。

示例

Declare @S varchar(500) = '11111122111131111111'
Declare @C varchar(10)  = '1'


Select Seq=Row_Number() over (Order by Seq)
      ,Cnt=count(*)
 From (
        Select N
              ,S = substring(@S,N,1)
              ,Seq = N - Row_Number() over (Order by N)
         From ( Select Top (len(@S)) 
                       N=Row_Number() Over (Order By (Select NULL)) 
                  From master..spt_values n1
              ) A
         Where substring(@S,N,1)=@C
      ) A
 Group By Seq
 Order By Seq

返回

Seq Cnt
1   6
2   4
3   7

答案 2 :(得分:0)

;WITH splitString(val) AS       
(
    -- convert the string to xml, seperating the elements by spaces
    SELECT    CAST('<r><i>' + REPLACE(@string,' ','</i><i>') + '</i></r>' AS XML)
)
SELECT  [Key],
        COUNT(*) [WordCount]
FROM    (   -- select all of the values from the xml created in the cte
            SELECT  p.value('.','varchar(100)') AS [Key]
            FROM    splitString
                    CROSS APPLY val.nodes('//i') t (p)) AS t
GROUP BY [Key]