[英]How to parse the following JSON to retrieve the name of the item in snowflake sql?
[
{
"itemId": "HWKDVCXKU5",
"name": "A",
"quantity": 1.000000000000000e+00,
"storeId": 1.150192000000000e+06,
"type": "structure"
},
{
"itemId": "FPK81M587X",
"name": "b",
"quantity": 1.000000000000000e+00,
"storeId": 1.150192000000000e+06,
"type": "structure"
},
{
"itemId": "L04WBQON3C",
"name": "C",
"quantity": 2.000000000000000e+00,
"storeId": 1.150192000000000e+06,
"type": "structure"
},
{
"itemId": "ULZFPY2UJN",
"name": "D",
"quantity": 2.000000000000000e+00,
"storeId": 1.150192000000000e+06,
"type": "structure"
},
我想要 2 列中的所有名稱和數量,我不知道如何編寫查詢。
所以使用子選擇來“制作數據”,然后使用 PARSE_JSON 和 FLATTEN 我們得到:
SELECT
f.value:name::text as name,
f.value:quantity::float as quanitiy
FROM (
SELECT PARSE_JSON('[
{
"itemId": "HWKDVCXKU5",
"name": "A",
"quantity": 1.000000000000000e+00,
"storeId": 1.150192000000000e+06,
"type": "structure"
},
{
"itemId": "FPK81M587X",
"name": "b",
"quantity": 1.000000000000000e+00,
"storeId": 1.150192000000000e+06,
"type": "structure"
},
{
"itemId": "L04WBQON3C",
"name": "C",
"quantity": 2.000000000000000e+00,
"storeId": 1.150192000000000e+06,
"type": "structure"
},
{
"itemId": "ULZFPY2UJN",
"name": "D",
"quantity": 2.000000000000000e+00,
"storeId": 1.150192000000000e+06,
"type": "structure"
}]') as json
) j
,TABLE(FLATTEN(input=>json)) f;
這使:
姓名 | 數量 |
---|---|
一個 | 1 |
b | 1 |
C | 2 |
D | 2 |
另一種查看完全相同代碼的方法,但將 JSON 移至 CTE(因此它看起來像普通表)
WITH data_cte AS (
SELECT PARSE_JSON('[
{
"itemId": "HWKDVCXKU5",
"name": "A",
"quantity": 1.000000000000000e+00,
"storeId": 1.150192000000000e+06,
"type": "structure"
},
{
"itemId": "FPK81M587X",
"name": "b",
"quantity": 1.000000000000000e+00,
"storeId": 1.150192000000000e+06,
"type": "structure"
},
{
"itemId": "L04WBQON3C",
"name": "C",
"quantity": 2.000000000000000e+00,
"storeId": 1.150192000000000e+06,
"type": "structure"
},
{
"itemId": "ULZFPY2UJN",
"name": "D",
"quantity": 2.000000000000000e+00,
"storeId": 1.150192000000000e+06,
"type": "structure"
}]') as json
)
SELECT
f.value:name::text as name,
f.value:quantity::float as quanitiy
FROM data_cte j
,TABLE(FLATTEN(input=>json)) f;
這是我解決您問題的方法:
create or replace stage my_json_stage;
PUT file:///Users/athakur/Downloads/Chrome Downloads/test.json @my_json_stage auto_compress=false;
create or replace table test_json
( my_value variant);
copy into test_json from @my_json_stage/test.json
file_format = (type = JSON strip_outer_array = true)
ON_Error = Continue;
select * from test_json;
select $1:name::string, $1:quantity::string from test_json;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.