无法使用google bigquery(标准)

时间:2017-10-19 19:04:53

标签: r google-bigquery unnest

我有一个嵌套表,我无法访问使用标准google bigquery的所有字段。

例如,此查询失败

SELECT  *
FROM 
    (
    SELECT
           rev_info.user.id as player_id,
           rev_info.purchase.total.currency as currency,
           rev_info.purchase.total.amount as REV
          ,rev_info.purchase.virtual_items.items.sku     as sku 
    FROM `gcs.rev`
    )
WHERE currency = 'USD'

有错误

  

"错误:无法访问类型为ARRAY>的值的字段sku在[9:59]"

然而

SELECT  *
FROM 
    (
    SELECT
           rev_info.user.id as player_id,
           rev_info.purchase.total.currency as currency,
           rev_info.purchase.total.amount as REV
          --,rev_info.purchase.virtual_items.items.sku   as sku 
    FROM `gcs.rev`
    )
WHERE currency = 'USD'

此查询没问题。

另请注意

SELECT
       rev_info.purchase.virtual_items.items.sku     as sku 
FROM `gcs.rev`

失败并出现与上述相同的错误。

2 个答案:

答案 0 :(得分:1)

如果您的目标是为每个items数组元素获取一行,则可以在表和rev_info.purchase.virtual_items.items之间使用逗号(连接)运算符。例如,

SELECT *
FROM (
  SELECT
    rev_info.user.id as player_id,
    rev_info.purchase.total.currency as currency,
    rev_info.purchase.total.amount as REV,
    item.sku as sku 
  FROM `gcs.rev` t,
    t.rev_info.purchase.virtual_items.items item
)
WHERE currency = 'USD'

答案 1 :(得分:1)

扩展Elliott的答案 - 我想你首先需要UNNEST,但是你很可能需要汇总你的sku。否则你将获得相当多余(扁平化)的输出

   

我觉得下面是您可能需要的 - 它适用于BigQuery Standard SQL

#standardSQL
SELECT 
  player_id, 
  currency, 
  REV, 
  STRING_AGG(sku) SKUs
FROM (
  SELECT
    rev_info.user.id AS player_id,
    rev_info.purchase.total.currency AS currency,
    rev_info.purchase.total.amount AS REV,
    item.sku AS sku 
  FROM `gcs.rev` t,
  UNNEST(t.rev_info.purchase.virtual_items.items) item
)
WHERE currency = 'USD'
GROUP BY 1, 2, 3   

因此,所有sku都将显示为给定player_id的列表,以及金额和货币

根据Elliott的评论/建议添加

#standardSQL
SELECT
  rev_info.user.id AS player_id,
  rev_info.purchase.total.currency AS currency,
  rev_info.purchase.total.amount AS REV,
  (SELECT STRING_AGG(item.sku) 
     FROM UNNEST(t.rev_info.purchase.virtual_items.items) item
  ) AS SKUs 
FROM `gcs.rev` t,
WHERE currency = 'USD'