我想使用两个表创建 JSON。 我是一个 SQL 初学者,所以很难创建。这是谷歌翻译。抱歉。
create table data_tb (city text , val_2020 numeric , val_2021 numeric);
insert into data_tb values ('korea seoul', 80.00, 73.91);
insert into data_tb values ('korea busan', 79.28, 70.27);
create table unit_tb (unit text, ranges text);
insert into unit_tb values ('%', '0, 10, 20, 30, 40, 50, 60, 70, 80');
我想使用 SQL 创建这样的 JSON
{
data:[
{
label: 'val_2020',
chartData: [{
key: 'korea seoul',
value: 80.00
},
{
key: 'korea busan',
value: 79.28
}
]
},
{
label: 'val_2021',
chartData: [{
key: 'korea seoul',
value: 73.91
},
{
key: 'korea busan',
value: 70.27
}
]
}
],
unit: '%',
ranges: [0, 10, 20, 30, 40, 50, 60, 70, 80]
}
有点复杂和混乱。也许数据设计可以优化一下。
select jsonb_build_object(
'data', jsonb_build_array(
jsonb_build_object(
'label', 'val_2020',
'chartData', (select jsonb_agg(t)
from (select city as key, val_2020 as value from data_tb) t)),
jsonb_build_object( 'label', 'val_2021',
'chartData', (select jsonb_agg(t)
from (select city as key, val_2021 as value from data_tb) t))),
'unit', (select unit from unit_tb),
'ranges', ('{'||(select ranges from unit_tb)||'}')::integer[]
);
DB Fiddle 演示