展平并重建 JSON 雪花

Flatten and reconstruct JSON Snowflake

我还在学习 Snowflake,非常感谢任何帮助。

我有一个专栏,我们称它为'result'。

{
  "catalog": [
    {
      "img_href": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179361.jpg",
      "name": "ADITI HAND BLOCKED PRINT",
      "price": 16
    },
    {
      "img_href": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179330.jpg",
      "name": "TORBAY HAND BLOCKED PRINT",
      "price": 17
    },
    {
      "img_href": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179362.jpg",
      "name": "ADITI HAND BLOCKED PRINT",
      "price": 18
    }
  ],
  "datetime": 161878993658
  "catalog_id": 1
}

我想把它压平重建如下

[
  {
    "datetime": 161878993658,
    "url": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179361.jpg"
  },
  {
    "datetime": 161878993658,
    "url": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179330.jpg"
  },
  {
    "datetime": 161878993658,
    "url": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179362.jpg"
  },
]

下面会做这个。您不需要 CTE,因此将其删除并将 tbl 的使用替换为您的 table 的名称,并将 json 的使用替换为您的变体列。

/*delete this line*/ with tbl as (select parse_json() json from values('{"catalog":[{"img_href":"https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179361.jpg","name":"ADITI HAND BLOCKED PRINT","price":16},{"img_href":"https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179330.jpg","name":"TORBAY HAND BLOCKED PRINT","price":17},{"img_href":"https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179362.jpg","name":"ADITI HAND BLOCKED PRINT","price":18}],"datetime":161878993658,"catalog_id":1}'))

select array_agg(new_col) reconstructed
from (
  /* replace json and tbl */ select object_construct('datetime', json:datetime, 'url', obj.value:img_href) new_col, json:catalog_id catalog_id
  from tbl, lateral flatten(json:catalog) obj
) group by catalog_id;

输出

[
  {
    "datetime": 161878993658,
    "url": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179361.jpg"
  },
  {
    "datetime": 161878993658,
    "url": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179330.jpg"
  },
  {
    "datetime": 161878993658,
    "url": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179362.jpg"
  }
]