简体   繁体   English

以 JSON 的形式从 Presto 中提取结果

[英]Extract results from Presto in the form of JSON

I have a presto view from where I need to create nested JSON.我有一个需要创建嵌套 JSON 的预览视图。 I have tried with the below query:我尝试过以下查询:

SELECT CAST(CAST(ROW('Sales (PTD)' as Ttl,unsale as Val) AS ROW(v1 VARCHAR, v2 VARCHAR)) AS JSON)
from metrics_v where time_frame='PTD';

I need a JSON result like below:我需要一个 JSON 结果如下:

"SlsPTD": {
    "Ttl": "Sales (PTD)",
    "Val": "103.27290344238281"
  }

But it is currently throwing error: SQL Error [1]: Query failed (#20220725_063102_03638_j2tav): line 1:36: mismatched input 'as'.但它目前正在抛出错误:SQL 错误 [1]:查询失败(#20220725_063102_03638_j2tav):第 1:36 行:输入“as”不匹配。 Expecting: ')', ','期望:')',','

How to get the expected result?如何得到预期的结果?

But it is currently throwing error: SQL Error 1 : Query failed (#20220725_063102_03638_j2tav): line 1:36: mismatched input 'as'.但它目前正在抛出错误:SQL 错误1 :查询失败(#20220725_063102_03638_j2tav):第 1:36 行:输入“as”不匹配。 Expecting: ')', ','期望:')',','

the issue here is incorrect syntax for ROW instantioation, correct query can look like:这里的问题是ROW实例化的语法不正确,正确的查询可能如下所示:

SELECT CAST(
        CAST(
            ROW('Sales (PTD)', unsale) AS ROW(Ttl VARCHAR, Val VARCHAR)
        ) AS JSON
    )
from dataset
where time_frame = 'PTD';

But ROW is incorrect data structure here, cause presto does not treat it as key-value pairs but rather as a collection of values (ie an array, see the cast to json doc).但是ROW在这里是不正确的数据结构,因为 presto 不将其视为键值对而是将其视为值的集合(即数组,请参阅转换为 json文档)。 You can use MAP :您可以使用MAP

-- sample data
WITH dataset(unsale, time_frame) AS (
    VALUES ('103.27290344238281', 'PTD')
) 

-- query
SELECT CAST(
        map(
            array [ 'SlsPTD' ],
            array [ map(array [ 'Ttl', 'Val' ], array [ 'Sales (PTD)', unsale ]) ]
        ) AS JSON
    )
from dataset
where time_frame = 'PTD';

Output: Output:

_col0 _col0
{"SlsPTD":{"Ttl":"Sales (PTD)","Val":"103.27290344238281"}} {"SlsPTD":{"Ttl":"销售 (PTD)","Val":"103.27290344238281"}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM