【问题标题】:How do I split a string column into multi rows of single words & word pairs in BigQuery SQL?如何在 BigQuery SQL 中将字符串列拆分为多行单个单词和单词对?
【发布时间】:2018-03-21 14:53:36
【问题描述】:

我正在尝试(未成功)将 Google BigQuery 中的字符串列拆分为包含所有单个单词和所有单词对的行(彼此相邻且按顺序排列)。我还需要维护 IndataTable 中单词的 ID 字段。两个记录集都有 2 列。

IndataTable 作为 IDT
ID WordString
1个苹果香蕉梨
2根胡萝卜
3蓝红绿黄

OutdataTable 作为 ODT
ID WordString
1 个苹果
1根香蕉
1 个梨
1个苹果香蕉
1个香蕉梨
2根胡萝卜
3 蓝色
3红色
3绿色
3 黄色
3蓝红
3红绿
3 绿黄(仅对彼此相邻)

这在 BigQuery SQL 中可行吗?

编辑/添加:
到目前为止,这就是我所拥有的,可以将其拆分为单个单词。我真的很难弄清楚如何将其扩展到单词对。我不知道这是否可以对其进行修改,或者我完全需要一种新方法。

SELECT ID, split(WordString,' ') as Words
FROM (
  select * 
     from 
     (select ID, WordString from IndataTable)
)

【问题讨论】:

  • 您能添加到目前为止您尝试过的代码吗?
  • 刚刚添加了适用于单个单词的现有代码。

标签: google-bigquery bigquery-standard-sql legacy-sql


【解决方案1】:

以下是 BigQuery 标准 SQL

#standardSQL
WITH IndataTable AS (
  SELECT 1 id, 'apple banana pear' WordString UNION ALL
  SELECT 2, 'carrot' UNION ALL
  SELECT 3, 'blue red green yellow' 
), words AS (
  SELECT id, word, pos
  FROM IndataTable, UNNEST(SPLIT(WordString,' ')) AS Word WITH OFFSET pos
), pairs AS (
  SELECT id, CONCAT(word, ' ', LEAD(word) OVER(PARTITION BY id ORDER BY pos)) pair
  FROM words
)
SELECT id, word AS WordString FROM words UNION ALL
SELECT id, pair AS WordString FROM pairs
WHERE NOT pair IS NULL
ORDER BY id  

结果符合预期:

Row id  WordString   
1   1   apple    
2   1   banana   
3   1   pear     
4   1   apple banana     
5   1   banana pear  
6   2   carrot   
7   3   blue     
8   3   red  
9   3   green    
10  3   yellow   
11  3   blue red     
12  3   red green    
13  3   green yellow     

【讨论】:

  • 非常感谢。这正是我所需要的,它非常适合我的用例。我不是专业的程序员,我想我可以花一整天以上的时间来解决这个问题。感谢您的帮助米哈伊尔。希望你有一个美好的一天。
猜你喜欢
  • 2022-01-18
  • 2011-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-22
  • 2011-06-12
  • 2011-11-03
相关资源
最近更新 更多