无法正确查询bigquery-不支持引用其他表的相关子查询

时间:2019-01-15 08:40:41

标签: sql google-bigquery

我桌子上有这样的东西,

+---------+------------+-----------------+-----------------------------+
|   id    | event_name | event_params.key| event_params.value.int_value|
+---------+------------+-----------------+-----------------------------+
|    1    |   click    |      stars      |            12               |
+---------+------------+-----------------+-----------------------------+
|         |            |     level       |             1               |
+---------+------------+-----------------+-----------------------------+
|    5    |   click    |      stars      |            20               |
+---------+------------+-----------------+-----------------------------+
|         |            |     level       |             1               |
+---------+------------+-----------------+-----------------------------+
|    8    |   click    |      stars      |            100              |
+---------+------------+-----------------+-----------------------------+
|         |            |     level       |             2               |
+---------+------------+-----------------+-----------------------------+

我想要平均所有恒星的平均水平,所以做了类似的事情

SELECT level,
     (SELECT AVG((
        SELECT CAST(d.value.string_value as INT64) 
        FROM UNNEST(event_params)as d 
        WHERE (d.key = "stars"
      ))) as avg_star_at_level 
      FROM `table1`,UNNEST(event_params) as h 
      WHERE event_name = "click" AND (h.key = "level") AND
            h.value.int_value = level)
FROM UNNEST(GENERATE_ARRAY(1,100)) as level

但是我得到了类似这样的信息:“不支持引用其他表的相关子查询”。

所以我尝试了这个

SELECT level,avg_token_at_level 
FROM UNNEST(GENERATE_ARRAY(1,100)) as level,
     (SELECT AVG((
        SELECT CAST(d.value.string_value as INT64) 
        FROM UNNEST(event_params)as d 
        WHERE (d.key = "stars"
      ))) as avg_star_at_level 
      FROM `table1`,UNNEST(event_params) as h 
      WHERE event_name = "click" AND (h.key = "level") 
      AND h.value.int_value = level)

我得到了无法识别的名字:等级。 如何正确,有效地查询?

我试图产生的结果:

+---------+------------+
|  level  |    avg     |
+---------+------------+
|    1    |    16.0    |
+---------+------------+
|    2    |    100.0   |
+---------+------------+

1 个答案:

答案 0 :(得分:1)

以下是用于BigQuery标准SQL

#standardSQL
SELECT AVG(avg_star_at_level) avg_all_star FROM (
  SELECT 
    (SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'level') level,
    AVG((SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'stars')) avg_star_at_level
  FROM `project.dataset.table1` 
  GROUP BY level
)  

有结果

Row avg_all_star     
1   58.0