首页 > 解决方案 > 有没有办法修改和重命名 BigQuery 中记录内的列,然后使该列保持与以前相同的名称和位置?

问题描述

RECORD在 BigQuery 中有一个结构:

Parent
|___Child_1
|___Child_2
|___Child_3
|___...

Child_1是类型TIMESTAMP,所以我想将它从TIMESTAMP字符串转换为INT64表示自 Unix 纪元以来的毫秒数。这是通过unix_millis函数完成的。

我无法为嵌套字段完成此操作。以下是我的尝试:

select *, unix_millis(parent.child_1) as parent.child_1 from `dataset.table`

当我尝试上述操作时,BigQuery 中的查询编辑器在“as parent.child_1”中为“child_1”下划线,并给出了错误Syntax error: Expected end of input but got "."

为什么我希望这会起作用,因为对于非嵌套字段,可以使用unix_millis然后使用AS运算符重命名列。

那么我将如何执行该unix_millis功能,然后确保生成的列与RECORD以前一样具有相同的名称和位置?

标签: google-bigquery

解决方案


以下是 BigQuery 标准 SQL

#standardSQL
SELECT * 
  REPLACE((
    SELECT AS STRUCT * REPLACE(UNIX_MILLIS(child1) AS child1)
    FROM UNNEST([parent])
  ) AS parent)
FROM `project.dataset.table`   

您可以使用一些简化的虚拟数据进行测试,如以下示例所示

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 1 id, STRUCT<child1 TIMESTAMP, child2 STRING, child3 INT64>(CURRENT_TIMESTAMP(), 'test1', 123) parent UNION ALL
  SELECT 2, STRUCT<child1 TIMESTAMP, child2 STRING, child3 INT64>(CURRENT_TIMESTAMP(), 'test2', 456)
)
SELECT * 
  REPLACE((
    SELECT AS STRUCT * REPLACE(UNIX_MILLIS(child1) AS child1)
    FROM UNNEST([parent])
  ) AS parent)
FROM `project.dataset.table`

带输出

Row id  parent.child1   parent.child2   parent.child3    
1   1   1599154064128   test1           123  
2   2   1599154064128   test2           456    

而原始数据是

Row id  parent.child1                   parent.child2   parent.child3    
1   1   2020-09-03 17:29:09.512794 UTC  test1           123  
2   2   2020-09-03 17:29:09.512794 UTC  test2           456  

推荐阅读