简体   繁体   中英

BigQuery: How do I check for every string element of column1 whether it is contained in column2?

I am using BigQuery. My data looks like this, I start with Table1 and Table2:

Table1

Str1
"a"
"b"

Table2

id Str2
1 "car"
2 "apple"
3 "banana"
4 "bob"

How can I design my query to get Table3?

It has the Table2.id if the value from Table1 is found as substring in Table2.Str2.

Table3

a b
1 0
2 0
3 3
0 4

Thank you!

Consider below approach

select * from (
  select id, str1, regexp_contains(str2, str1) contained
  from table2, table1
)
pivot (min(contained) for str1 in ('a', 'b'))        

if applied to sample data in your question - output is

在此处输入图像描述

In case if you actually need output look exact as in your question - use below

select if(a, id, 0) a, if(b, id, 0) b from (
  select id, str1, regexp_contains(str2, str1) contained
  from table2, table1
)
pivot (min(contained) for str1 in ('a', 'b'))           

in this case - output is

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM