【问题标题】:How to create a new table with nested data in big query from another tables?如何在另一个表的大查询中创建一个包含嵌套数据的新表?
【发布时间】:2021-03-26 00:38:57
【问题描述】:

我在 google bigquery 手册中找到了很多创建嵌套数据的示例,但没有从其他表中执行此操作的示例。

我想使用两个现有表(例如行星和卫星表)创建一个包含嵌套数据的新表(例如 solar_system_moons_nested)(编写 SQL 语句以生成嵌套数据)。我希望新表如下所示:

我如下创建月球和行星表:

  1. 月亮桌

  1. 行星表:

是否可以从现有表中创建嵌套表?任何帮助将不胜感激。

这是我制作新表格的方法(如下):

WITH solar_system_moons_nested AS (
  SELECT p.planet,
          STRUCT(moon ,Distance_from_Planet__km_,Diameter__km_) AS moons, 
          from test.planets p inner join test.moons m on m.planet=p.planet
)

select * from solar_system_moons_nested

下面是它的样子:

如您所见,选择没有达到我的预期。

【问题讨论】:

    标签: google-cloud-platform google-bigquery bigdata


    【解决方案1】:

    如果你想要的只是一个嵌套结构,你可以使用 array_agg 并执行如下操作

    WITH solar_system_moons_nested AS (
      SELECT p.planet,
              ARRAY_AGG(STRUCT(moon ,Distance_from_Planet__km_,Diameter__km_)) AS moons, 
              from test.planets p inner join test.moons m on m.planet=p.planet
      GROUP BY 1
    )
    
    select * from solar_system_moons_nested
    
    
    

    更多关于array_agg的信息在这里https://cloud.google.com/bigquery/docs/reference/standard-sql/aggregate_functions

    【讨论】:

      【解决方案2】:

      使用array_agg构造数组:

      WITH solar_system_moons_nested AS (
        SELECT 
          p.planet,
          array_agg(STRUCT(moon ,Distance_from_Planet__km_,Diameter__km_)) AS moons, 
        from test.planets p inner join test.moons m on m.planet=p.planet
        group by p.planet
      )
      
      select * from solar_system_moons_nested
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-03
        • 2020-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-05
        • 1970-01-01
        相关资源
        最近更新 更多