BigQuery check for array overlap

前端 未结 1 427
余生分开走
余生分开走 2021-01-24 16:04

So I\'m writing a BigQuery query and basically just need to be able to check if any of a number of strings are present as elements in one of the columns of the table, where the

1条回答
  •  孤街浪徒
    2021-01-24 16:39

    Below are two examples.

    First assuming you have your strings in another table strings

    #standardSQL
    WITH yourTable AS (
      SELECT 1 AS id, ['abc', 'def', 'xyz'] AS column UNION ALL
      SELECT 2, ['123', '456', '789'] UNION ALL
      SELECT 3, ['135', '246', '369'] 
    ),
    strings AS (
      SELECT 'abc' AS str UNION ALL
      SELECT '123' UNION ALL
      SELECT '456'
    )
    SELECT *
    FROM yourTable
    WHERE (SELECT COUNT(1) FROM UNNEST(column) AS col JOIN strings ON col = str) > 0  
    

    You can add below to SELECT list if you need to see how many strings are matching

    (SELECT COUNT(1) FROM UNNEST(column) AS col JOIN strings ON col = str) AS cnt
    

    Second example assumes you have list of strings packed in Array

    #standardSQL
    WITH yourTable AS (
      SELECT 1 AS id, ['abc', 'def', 'xyz'] AS column UNION ALL
      SELECT 2, ['123', '456', '789'] UNION ALL
      SELECT 3, ['135', '246', '369'] 
    ),
    strings AS (
      SELECT ['abc', 'def', '456'] AS strs
    )
    SELECT yourTable.*
    FROM yourTable, strings
    WHERE (SELECT COUNT(1) FROM UNNEST(column) AS col JOIN UNNEST(strs) AS str ON col = str) > 0   
    

    Same as in first example - you can add below to SELECT list to see matches count

    (SELECT COUNT(1) FROM UNNEST(column) AS col JOIN UNNEST(strs) AS str ON col = str) AS cnt
    

    0 讨论(0)
提交回复
热议问题