将 table 中的列合并到 JSON 对象中

Combine columns from a table into a JSON object

我在雅典娜有一个 table 数据

type   state   city  zipcode
-------------------------------
hot     az     phx    85281
hot     tx     dal    12345
cool    wa     sea    67890
cool    ny     nyc    67856

我希望输出像

type   Data 
-------------
hot    {state: az, city:phx, zipcode: 85281}
hot    {state: tx, city:dal, zipcode: 12345}
cool   {state: wa, city:sea, zipcode: 67890}
cool   {state: ny, city:nyc, zipcode: 67856}

我正在尝试使用聚合函数,但我无法使用它。

SELECT 类型,CAST(MAP(ARRAY['state', 'city', 'zipcode'], ARRAY[state,city,zipcode] ) AS JSON) 从 "test"."alldata"

但是查询失败。

如果您有 mysql 5.7 或更高版本:使用

SELECT `type`,json_object('state', `state`, 'city', `city`,'zipcode',`zipcode`)
FROM alldata;
CREATE TABLE alldata
    (`type` varchar(4), `state` varchar(2), `city` varchar(3), `zipcode` int)
;
    
INSERT INTO alldata
    (`type`, `state`, `city`, `zipcode`)
VALUES
    ('hot', 'az', 'phx', 85281),
    ('hot', 'tx', 'dal', 12345),
    ('cool', 'wa', 'sea', 67890),
    ('cool', 'ny', 'nyc', 67856)
;
✓

✓
SELECT `type`,json_object('state', `state`, 'city', `city`,'zipcode',`zipcode`)
FROM alldata;
type | json_object('state', `state`, 'city', `city`,'zipcode',`zipcode`)
:--- | :----------------------------------------------------------------
hot  | {"city": "phx", "state": "az", "zipcode": 85281}                 
hot  | {"city": "dal", "state": "tx", "zipcode": 12345}                 
cool | {"city": "sea", "state": "wa", "zipcode": 67890}                 
cool | {"city": "nyc", "state": "ny", "zipcode": 67856}                 

db<>fiddle here

对于蜂巢:

with mydata as (
select stack(4,
    'hot', 'az', 'phx', 85281,
    'hot', 'tx', 'dal', 12345,
    'cool', 'wa', 'sea', 67890,
    'cool', 'ny', 'nyc', 67856
) as  (type, state, city, zipcode)
)

select type, map('state', state, 'city', city,'zipcode',zipcode) as data
 from mydata;

结果:

type    data
hot     {"state":"az","city":"phx","zipcode":"85281"}
hot     {"state":"tx","city":"dal","zipcode":"12345"}
cool    {"state":"wa","city":"sea","zipcode":"67890"}
cool    {"state":"ny","city":"nyc","zipcode":"67856"}

如果需要字符串类型,使用brickhouse库:

add jar /path/brickhouse-0.7.0-SNAPSHOT.jar; --compile jar and load it to the distributed cache
CREATE TEMPORARY FUNCTION to_json AS 'brickhouse.udf.json.ToJsonUDF';

select type, to_json(map('state', state, 'city', city,'zipcode',zipcode)) as data
 from mydata;