BigQuery-执行从SQL查询生成的SQL查询

时间:2019-03-08 15:03:49

标签: google-bigquery

我正在处理BigQuery中的动态查询,该查询将为通过json对象传递的每个记录创建x列数。我已编写查询以编程方式生成将具有x列的查询,但是我不知道如何执行生成查询而不复制并将其粘贴到编辑器中。有没有一种方法可以执行另一个查询生成的查询?

我知道可以用Python或任何其他编程语言生成整个查询,但是对于这种特定用例,我希望将所有内容保留在SQL中。

当我执行此查询时,它将在下面输出生成的查询

with names_ids as (
  SELECT
    JSON_EXTRACT_SCALAR(json_text, '$.name') as name,
    JSON_EXTRACT_SCALAR(json_text, '$.id') as id
  FROM UNNEST([
    '{"id": "123456", "name": "test 1"}',
    '{"id": "789456", "name": "test 2"}',
    '{"id": "456123", "name": "test 3"}'
    ]) as json_text
)

select  
  concat(
    'select user_id, event_time, ',
    string_agg(
      concat(
      ' min(case when activity_id = ', json_extract(a.json_data, '$.id'), ' then 1 else end) as has_', lower(replace(json_extract_scalar(a.json_data, '$.name'), ' ', '_'))
      )
    )
  ) as query
  from (
    select to_json_string(a) as json_data
    from names_ids as a
    )

以上查询的输出:

select user_id, event_time,  min(case when activity_id = "123456" then 1 else end) as has_test_1, min(case when activity_id = "789456" then 1 else end) as has_test_2, min(case when activity_id = "456123" then 1 else end) as has_test_3

如何执行上述查询输出?

0 个答案:

没有答案