Presto 构建 JSON 个具有不同数据类型的数组
Presto Build JSON Array with Different Data Types
我的目标是获得一个 JSON varchar name
、varchar age
数组和一个 books_read
(array(varchar)) 的 LIST for EACH id
books_read
具有以下格式:["book1", "book2"]
给出的例子Table:
id
name
age
books_read
1
John
21
["book1", "book2"]
预期输出:
id
info
1
[{"name":"John", "age":"21", "books_read":["book1", "book2"]}]
当我使用以下查询时出现错误 (All ARRAY elements must be the same type: row(varchar, varchar)
),因为 books_read 不是 name 和 age 之类的 varchar 类型。
select id,
array_agg(CAST(MAP_FROM_ENTRIES(ARRAY[
('name', name),
('age', age),
('books_read', books)
]) AS JSON)) AS info
from tbl
group by id
是否有允许多种类型作为数组输入的替代方法?
我也试过 MAP_CONCAT(MAP_AGG(name), MAP_AGG(age), MULTIMAP_AGG(books_read))
但它也给我带来了 books_read
列的问题: Unexpected parameters
函数 map_concat
在将数据放入地图之前将数据投射到 json:
-- sample data
WITH dataset (id, name, age, books_read) AS (
VALUES (1, 'John', 21, array['book1', 'book2'])
)
-- query
select id,
cast(
map(
array [ 'name', 'age', 'books_read' ],
array [ cast(name as json), cast(age as json), cast(books_read as json) ]
) as json
) info
from dataset
输出:
id
info
1
{"age":21,"books_read":["book1","book2"],"name":"John"}
我的目标是获得一个 JSON varchar name
、varchar age
数组和一个 books_read
(array(varchar)) 的 LIST for EACH id
books_read
具有以下格式:["book1", "book2"]
给出的例子Table:
id | name | age | books_read |
---|---|---|---|
1 | John | 21 | ["book1", "book2"] |
预期输出:
id | info |
---|---|
1 | [{"name":"John", "age":"21", "books_read":["book1", "book2"]}] |
当我使用以下查询时出现错误 (All ARRAY elements must be the same type: row(varchar, varchar)
),因为 books_read 不是 name 和 age 之类的 varchar 类型。
select id,
array_agg(CAST(MAP_FROM_ENTRIES(ARRAY[
('name', name),
('age', age),
('books_read', books)
]) AS JSON)) AS info
from tbl
group by id
是否有允许多种类型作为数组输入的替代方法?
我也试过 MAP_CONCAT(MAP_AGG(name), MAP_AGG(age), MULTIMAP_AGG(books_read))
但它也给我带来了 books_read
列的问题: Unexpected parameters
函数 map_concat
在将数据放入地图之前将数据投射到 json:
-- sample data
WITH dataset (id, name, age, books_read) AS (
VALUES (1, 'John', 21, array['book1', 'book2'])
)
-- query
select id,
cast(
map(
array [ 'name', 'age', 'books_read' ],
array [ cast(name as json), cast(age as json), cast(books_read as json) ]
) as json
) info
from dataset
输出:
id | info |
---|---|
1 | {"age":21,"books_read":["book1","book2"],"name":"John"} |