如何进行这样的查询?

时间:2018-07-27 10:35:26

标签: google-bigquery

对不起,标题不是很明确,但我不知道如何正确解释。

成功完成游戏中的关卡后,我正在跟踪事件。我跟踪级别号(NumNivel)和尝试次数(NumIntentos)

The data is saved with this structure:

问题是我想拥有这样的输出数据:

等级编号/ 1次尝试/ 2次尝试/ ... / 10次以上

我运行了这样的查询:

SELECT 
  Level AS Level_Number,
  MAX((value=1) * Levels) AS i1,
  MAX((value=2) * Levels) AS i2,
  MAX((value=3) * Levels) AS i3,
  MAX((value=4) * Levels) AS i4,
  MAX((value=5) * Levels) AS i5,
  MAX((value=6) * Levels) AS i6,
  MAX((value=7) * Levels) AS i7,
  MAX((value=8) * Levels) AS i8,
  MAX((value=9) * Levels) AS i9,
  MAX((value=10) * Levels) AS i10,

FROM (
    SELECT
      COUNT(event_name) AS Levels,
      event_params.key AS Level,
      event_params.value.int_value AS value
    FROM
      [tal:analytics_151354869.events_20180726]
    WHERE
      event_name = 'LevelComplete'
      AND event_params.key = 'NumNivel'
      AND app_info.id = 'com.game'
    GROUP BY Level, value
    )
GROUP BY Level_number

但是我拥有的是按级别数计数的级别。

可以做我想做的事吗?

1 个答案:

答案 0 :(得分:0)

您的表格结构对您而言并不容易。由于您要查找的值都存储在同一个非结构化数组中,因此您必须先进行Flatten(平展)和Join(连接)两次才能获取这两个信息。

我认为您需要类似以下查询的内容(删除“ source_table”位并替换为表)。此查询与event_params数组一起联接一次,并选择LevelNumber(NumNivel),第二次联接与同一行中的NumAttempts(NumIntentos)。

WITH source_table AS (
SELECT * FROM UNNEST(ARRAY<STRUCT<event_name STRING, event_params ARRAY<STRUCT<key STRING, value STRUCT<int_value INT64>>> >>
     [('LevelComplete', [('NumNivel', STRUCT(1)), ('NumIntentos', STRUCT(3))]),
      ('LevelComplete', [('NumNivel', STRUCT(2)), ('NumIntentos', STRUCT(5))])])
)
SELECT a.value.int_value AS LevelNumber, b.value.int_value AS NumAttempts
FROM source_table, UNNEST(event_params) a, UNNEST(event_params) b
WHERE event_name = 'LevelComplete'
AND a.key = 'NumNivel' AND b.key = 'NumIntentos'
;

参考: https://cloud.google.com/bigquery/docs/reference/standard-sql/arrays#querying-struct-elements-in-an-array