Google 大查询中倒数第三个子字符串

Third substring from the end in Google Big Query

我使用标准 sql 并想从末尾提取第三个子字符串。

Example Input: "Search-site-variable-brand-0-city-none-18053517"
Output: "city"

这可能会成功:

WITH data AS(
  select "Search-site-variable-brand-0-city-none-18053517" as Input
)

SELECT
  CASE WHEN ARRAY_LENGTH(SPLIT(Input, '-')) > 3 THEN SPLIT(Input, '-')[OFFSET(ARRAY_LENGTH(SPLIT(Input, '-')) - 3)] END word
FROM data

它 returns NULL 以防字符串没有拆分,比如空字符串。

我只是想指出,如果您计划将此转换应用于多个列,将逻辑拉入 UDF 可能会很有用。这是一个如何做到这一点的例子:

CREATE TEMP FUNCTION SecondSubstringFromEnd(s STRING) AS ((
  SELECT arr[SAFE_OFFSET(ARRAY_LENGTH(arr) - 3)]
  FROM (
    SELECT SPLIT(s, '-') AS arr
  )
));

WITH Input AS (
  SELECT 'Search-site-variable-brand-0-city-none-18053517' AS str UNION ALL
  SELECT 'a-b' UNION ALL
  SELECT 'w-x-yyy-z'
)
SELECT
  str,
  SecondSubstringFromEnd(str) AS second_substring_from_end
FROM Input;

BigQuery 标准的更多变体SQL:

#standardSQL
WITH YourTable AS(
  SELECT 'Search-site-variable-brand-0-city-none-18053517' AS Input UNION ALL
  SELECT 'Second-substring-from-the-end-in-Google-BigQuery' UNION ALL
  SELECT 'bigQuery-assign-a-value-to-table-1-based-on-table-2' UNION ALL
  SELECT 'Error-Message-Too-many-sources-provided-15285-Limit-is-10000' UNION ALL
  SELECT 'Google-Bigquery-data-import-from-Google-Analytics-360' UNION ALL
  SELECT 'Bigquery-Partitioning-data-past-2000-limit'
)
SELECT
  Input,
  REVERSE(SPLIT(REVERSE(Input), '-')[SAFE_ORDINAL(3)]) AS Output_1,
  ARRAY_REVERSE(SPLIT(Input, '-'))[SAFE_ORDINAL(3)] AS Output_2
FROM YourTable

“ARRAY_REVERSE”函数在这种情况下效果很好。

with input AS 
(
 SELECT "Search-site-variable-brand-0-city-none-18053517" AS to_reverse_string 
)

SELECT ARRAY_REVERSE(SPLIT(to_reverse_string, "-"))[SAFE_OFFSET(2)]
FROM input