BigQuery - 提取文本和子文本

时间:2015-09-03 08:26:08

标签: google-bigquery text-extraction

我在BigQuery中有一个关于日常发送的合同数量的表:

date        contract
2014-05-04  {jeans = 5, caps = 12, CDs = 1, Microwaves = 7, other = 6}
2014-05-05  {cups = 7, other = 5}

我需要提交有多少未分类合同(=其他)已发出。到现在为止,我通过下载CSV并在Excel中进行计算来实现。

我怎样才能在BQ中找到这样的表:

date        other_contracts
2014-05-04   6
2014-05-05   5

谢谢!

3 个答案:

答案 0 :(得分:2)

使用regexp_extract并查找数字序列...

SELECT
  *,
  REGEXP_EXTRACT(contract,r'other = (\d+)') AS Other
FROM (
  SELECT
    "2014-05-04" AS Date,
    "{jeans = 5, caps = 12, CDs = 1, Microwaves = 7, other = 6}" AS contract),
  (
  SELECT
    "2014-05-05" AS Date,
    "{cups = 7, other = 5}" AS contract)

答案 1 :(得分:2)

更通用的方法。 我认为可以提供帮助:

SELECT 
  Date,
  INTEGER(REGEXP_EXTRACT(Item, r'(\d+)')) AS Count,
  REGEXP_EXTRACT(Item, r'(\w+)') AS Item
FROM (
  SELECT Date, SPLIT(contract) as Item
  FROM 
    (SELECT "2014-05-04" AS Date, "{jeans = 5, caps = 12, CDs = 1, Microwaves = 7, other = 6}" AS contract),
    (SELECT "2014-05-05" AS Date, "{cups = 7, other = 5}" AS contract)
)
ORDER BY Date, Count DESC

结果是:

Date    Count   Item
5/4/2014    12  caps
5/4/2014    7   Microwaves
5/4/2014    6   other
5/4/2014    5   jeans
5/4/2014    1   CDs
5/5/2014    7   cups
5/5/2014    5   other

答案 2 :(得分:1)

如果您可以将第一个表格中的数据格式更改为JSON,那么您可以使用https://cloud.google.com/bigquery/query-reference?hl=en#jsonfunctions