在雪花上创建一个新的嵌套JSON专栏
我正在尝试将雪花表中的几列转换为嵌套的JSON,并尝试了Object_Construct
& 但是,无法创建嵌套的JSON
输入
ID | product_1 | Product_1 | Products_2 | PRODUCT_2_PCHERASE_DATE |
---|---|---|---|---|
100 | XCTMR | 01/02/2003 | - | array_construct |
product_1_purchase_date | : 2016 | XCTMR | 09/09/2021 |
输出:
ID | JSON_COMBIND |
---|---|
100 | [{“ PRODECT_1”:{“ NAME”:“ XCTMR”,“ PRODECT_1_PURCHASE_DATE”:“ 01/02/2003”}},{01/02/2003“}},{ product_2“:{“ name”:“ iopwer”,“ product_2_purchase_date”:“ 01/02/2005”}}}] |
200 | [{“ produck_1”:{“ name”:“ aqwyu”:“ aqwyu”,product_1_purchase_date“:” 11/20 /2016“}},{“ product_2”:{“ name”:“ xctmr”,“ product_2_purchase_date”:“ 09/09/2021”}}]] |
I'm trying to convert a few columns in Snowflake table into a nested JSON and have tried OBJECT_CONSTRUCT
& ARRAY_CONSTRUCT
- but, unable to create a nested JSON
Input:
id | product_1 | product_1_purchase_date | product_2 | product_2_purchase_date |
---|---|---|---|---|
100 | XCTMR | 01/02/2003 | IOPWER | 01/02/2005 |
200 | AQWYU | 11/20/2016 | XCTMR | 09/09/2021 |
Output:
id | json_combined |
---|---|
100 | [ { "product_1": { "name": "XCTMR", "product_1_purchase_date": "01/02/2003" } }, { "product_2": { "name": "IOPWER", "product_2_purchase_date": "01/02/2005" } } ] |
200 | [ { "product_1": { "name": "AQWYU", "product_1_purchase_date": "11/20/2016" } }, { "product_2": { "name": "XCTMR", "product_2_purchase_date": "09/09/2021" } } ] |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决方案,仅使用硬编码字段名称,只需要放置功能
array_construct
和object_construct
以正确的顺序。以下是具有更多动力的 -
object_agg
我们无法在另一个聚合功能中使用汇总函数,因此
我们需要多次进行聚合(在这里两次)。在此CTE中将划分更改为2列的数量。我们还可以在此处添加一个子问题来进行此计算,但是出于该解决方案的目的,我将其保留为硬编码。
CTE_1还在执行
undivot
产品相关的列的主要作业中,以进行动态分组。array_agg
。主要查询 -
最终输出从上方查询(具有动态) -
Solution, with hard-coding field-names only, just need to put functions
ARRAY_CONSTRUCT
andOBJECT_CONSTRUCT
in proper order.Below is with more dynamism -
another to be used as grouping criteria later in
OBJECT_AGG
Wecannot use aggregate function inside another aggregate function, so
we need to do aggregation multiple times (twice here). Change divide by 2 in this CTE to the number of product_x columns. We can also add a sub-query here to do this calculation, but for the purpose of this solution I've left it as hard-coded.
CTE_1 is also doing the main job of
UNPIVOT
product related column into rows for dynamic grouping.ARRAY_AGG
.Main query -
Final output from above query (with dynamism) -