代码之家  ›  专栏  ›  技术社区  ›  AI52487963

从分隔字段计算子字符串的出现次数

  •  1
  • AI52487963  · 技术社区  · 6 年前

    我有一些数据看起来像:

    Sequence, length
    abc, 1
    bat, 1
    abc > abc, 2
    abc > bat, 2
    ced > ced > ced > fan, 4
    

    我试图将各种字符串的频率视为此数据的一个新列。例如:

    Sequence, length, count_of_ced
    abc, 1, 0
    bat, 1, 0
    abc > abc, 2, 0
    abc > bat, 2, 0
    ced > ced > ced > fan, 4, 3
    

    length - array_length(split(replace(Sequence, "ced", ""), " > " )) as count_of_ced
    

    然而,该线的所有结果均为0。

    这是正确的方法吗?我已经用“>”和“>”上的字符串拆分测试了这两种方法,但两种方法都得到了0。我翻阅了一些Google Bigquery文档,但没有找到预构建的子字符串\ u count()函数或任何东西。

    2 回复  |  直到 6 年前
        1
  •  4
  •   Gordon Linoff    6 年前

    有一种行之有效的字符串长度方法:

    select (length(replace(sequence, 'ced', 'ced+')) - length(sequence)) as num_ced
    

    或者,您可以使用阵列:

    select array_length(regexp_extract_all(sequence, 'ced'))
    
        2
  •  0
  •   Mikhail Berlyant    6 年前

    SELECT ARRAY_LENGTH(SPLIT(Sequence, 'ced')) - 1   
    

    您可以使用问题中的虚拟数据进行测试,如下所示

    #standardSQL
    WITH `project.dataset.table` AS (
      SELECT 'abc' Sequence, 1 length UNION ALL
      SELECT 'bat', 1 UNION ALL
      SELECT 'abc > abc', 2 UNION ALL
      SELECT 'abc > bat', 2 UNION ALL
      SELECT 'ced > ced > ced > fan', 4 
    )
    SELECT Sequence, length, 
      ARRAY_LENGTH(SPLIT(Sequence, 'ced')) - 1 AS count_of_ced
    FROM `project.dataset.table`  
    

    结果是

    Row Sequence                length  count_of_ced     
    1   abc                     1       0    
    2   bat                     1       0    
    3   abc > abc               2       0    
    4   abc > bat               2       0    
    5   ced > ced > ced > fan   4       3