簡體   English   中英

使用另一個字段 BigQuery 在帶有分隔符的字段中獲取字符串的 Position

[英]Get Position of a String in a field with delimiters using ANOTHER field BigQuery

我想在一個字段中獲取一個單詞的 position,該字段具有以下數據,分隔符為“->”:

示例Col1 *

第 1 行| “行動 -> 蝙蝠 -> 貓 -> 日期 -> 吃”

第 2 行| “貓 -> 行動 -> 吃 -> BAT -> 日期”

我想提取 position 的值是另一列。

示例Col2

第 1 行|

第 2 行| 行為

Output 將是 -

第 1 行| 3

第 2 行| 2

我試過 regex_instr 和 instr 但他們都返回 position 我認為不是這個詞。

也試過這個,但它不起作用:

select *, array_length(split(regexp_extract( col1 , col2 ), '->'))

這個怎么樣:

select col1_item, col2, (case when trim(col1_item) = trim(col2) then col2_index else null end) as col2_index_found
from (select col1_item, col2, col2_index
from 
(
  select split("ACT->BAT->CAT->DATE->EAT", "->")as col1, 'CAT' as col2  
union all 
  select split("CAT->ACT->EAT->BAT->DATE", "->")as col1, 'ACT' as col2 

), unnest(col1) as col1_item WITH OFFSET AS col2_index 
)

這會給你想要的。 請注意:此偏移量是從零開始的數組索引。

考慮以下使用 arrays 的方法:

with sample_data as (
  select "ACT->BAT->CAT->DATE->EAT" as col1, "CAT" as col2
  union all select "CAT->ACT->EAT->BAT->DATE" as col1, "ACT" as col2

),
split_col1 as (
select 
  split(col1, "->") as col1_arr,
  col2,
from sample_data
)
select  
  if(col2 = col1_arr[offset(index)], index+1, null) as col2_index
from split_col1,
  unnest(generate_array(0,array_length(col1_arr)-1)) as index
where col2 = col1_arr[offset(index)]

Output:

在此處輸入圖像描述

考慮以下方法

select *, 
  array_length(split(regexp_extract(col1, r'(.*?)' || col2), '->')) as position
from your_table             

如果應用於您問題中的示例數據 - output 是

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM