首页 > 解决方案 > 在postgresql中以json格式在sql值中分组

问题描述

我的表中有如下数据

key         value
department  maths
department  science
class       one
class       two
book        science
book        maths
department  Tamil
book        SS
class       ten

在这张表中,我想得到如下所示

"department":{
department : maths,
department :scicence
},
"class":{
 class : one,
class :two
}

在 sql 它自己

标签: sqlpostgresql

解决方案


奇怪但可能。

警告输出是一个奇怪的伪 JSON,因为它有重复的键:

这可以满足您的要求:

create table data1 (
  key text,
  value text
);

insert into data1(key,value) values 
('department','maths'),
('department','science'),
('class','one'),
('class','two'),
('book','science'),
('book','maths'),
('department','Tamil'),
('book','SS'),
('class','ten');

select json_object_agg(key, joined_values)::text
  from (
    select key, json_object_agg(key, value) joined_values
      from data1
      group by key
  ) data_joined;

如果您不想在对象中重复键,您可以在里面使用一个数组

select json_object_agg(key, joined_values) 
  from (
    select key, json_agg(value) joined_values
      from data1
      group by key
  ) data_joined;

推荐阅读