0

我希望利用雪花中的变体功能。我是雪花的新手,从文档中看不到它是否支持我想做的事情。我想对一个表执行查询,在该表中我对具有标准类型(varchar、int ... ...)和从变量列中提取的值的列进行聚合(分组)。我的变体列将存储一组对象,如下所示:

{ "container": [
  {
    "param1": "value1a",
    "param2": "value2a",
    "param3": "value3a"
  },
  {
    "param1": "value1b",
    "param2": "value2b",
    "param3": "value3b"
  },
  {
    "param1": "value1c",
    "param2": "value2c",
    "param3": "value3c"
  }
]
}

在传统的 sql 模式中显示我正在尝试做的事情让我们说我有一个 1:n 的关系,其中容器是许多具有 fk(parent_id)的孩子,以指定 rel(对父母说)。这是我尝试在传统 sql/关系模型中表示的变体列上编写的一种查询:

SELECT P.column1, P.column2, C.param1, C.param2
FROM parent P
INNER JOIN Child c ON c.parent_id = p.id
GROUP BY 1, 2, 3
4

2 回答 2

0

您将需要使用FLATTEN命令来访问对象的各个部分。

container因此,要访问您将使用的三个参数

WITH input_tab AS (
  select PARSE_JSON('{ "container": [ {    "param1": "value1a",    "param2": "value2a",   "param3": "value3a"  },  {    "param1": "value1b",    "param2": "value2b",    "param3": "value3b"  },  {    "param1": "value1c",    "param2": "value2c",    "param3": "value3c"  }]}') as json
)
SELECT f.value:param1, 
    f.value:param2, 
    f.value:param3
    --,f.* -- here so you can see the other parts.
FROM input_tab AS i,
TABLE(flatten(input => i.json, path => 'container')) f;

给予:

F.VALUE:PARAM1  F.VALUE:PARAM2  F.VALUE:PARAM3
"value1a"   "value2a"   "value3a"
"value1b"   "value2b"   "value3b"
"value1c"   "value2c"   "value3c"

您需要使用 TRY_TO_x 或 AS_x 转换函数将其解析为类型数据。

于 2019-12-19T19:25:59.483 回答
0

很好的问题,不确定您打算使用哪个聚合函数,因为您的示例中没有它并且您的值是字符串,因此您的聚合函数是有限的。

温度表(方便使用)

CREATE OR REPLACE TEMP TABLE X
AS
SELECT PARSE_JSON(COLUMN1) AS C1
FROM VALUES 
($$
{ "container": [
  {
    "param1": "value1a",
    "param2": "value2a",
    "param3": "value3a"
  },
  {
    "param1": "value1b",
    "param2": "value2b",
    "param3": "value3b"
  },
  {
    "param1": "value1c",
    "param2": "value2c",
    "param3": "value3c"
  }
]
}$$);

选项1

SELECT C1
    ,F1.*
    ,F1.VALUE['param2']
FROM X
    ,LATERAL FLATTEN (INPUT => C1['container']) F1
;

选项 2

SELECT C1
    ,F1.*
    ,F2.*
FROM X
    ,LATERAL FLATTEN (INPUT => C1['container']) F1
    ,LATERAL FLATTEN (INPUT => F1.VALUE) F2
于 2019-12-19T19:26:54.217 回答