[英]How to select element from Varchar "JSON Array" in snowflake database?
I have a VARCHAR(16777216) column in a snowflake database table, that is structured as an array with JSON in it.我在雪花数据库表中有一个 VARCHAR(16777216) 列,它被构造为一个包含 JSON 的数组。
An example of a row in the column: [ {"Name":"John", "Last Name": "Doe"}, {"Name":"Frank", "Last Name": "Doe"}]
列中一行的示例:
[ {"Name":"John", "Last Name": "Doe"}, {"Name":"Frank", "Last Name": "Doe"}]
How do I use sql to select all of the Last Names in each row?如何使用 sql 选择每行中的所有姓氏?
Please note, this is a VARCHAR COLUMN.请注意,这是一个 VARCHAR 列。
You can flatten the JSON array and then extract the Last Name
field like this:您可以展平 JSON 数组,然后像这样提取
Last Name
字段:
WITH SampleData AS (
SELECT '[ {"Name":"John", "Last Name": "Doe"}, {"Name":"Frank", "Last Name": "Doe"}]' AS text
)
SELECT json_object.value:"Last Name" AS last_name
FROM SampleData, LATERAL FLATTEN (input => PARSE_JSON(text)) json_object;
This returns:这将返回:
LAST_NAME
"Doe"
"Doe"
In the query, the LATERAL FLATTEN
part is what indicates to return a row for each entry in the text after parsing it as JSON, and then in the SELECT
list, json_object.value
returns the value for this row, and :"Last Name"
returns the field named Last Name
from it.在查询中,
LATERAL FLATTEN
部分表示将文本中的每个条目解析为JSON 后返回一行,然后在SELECT
列表中, json_object.value
返回该行的值, :"Last Name"
从中返回名为Last Name
的字段。 The WITH SampleData (...)
part just creates some inline data with a VARCHAR
column named text
. WITH SampleData (...)
部分只是使用名为text
的VARCHAR
列创建一些内联数据。
If you want a single row for each input row, where the last names are in an array, you can use a query of this form:如果您希望每个输入行都有一行,其中姓氏在数组中,您可以使用以下形式的查询:
WITH SampleData AS (
SELECT '[ {"Name":"John", "Last Name": "Doe"}, {"Name":"Frank", "Last Name": "Doe"}]' AS text
)
SELECT ARRAY_AGG(json_object.value:"Last Name") AS last_names
FROM SampleData, LATERAL FLATTEN (input => PARSE_JSON(text)) json_object
GROUP BY text;
This returns:这将返回:
LAST_NAMES
[ "Doe", "Doe" ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.