在PostgreSQL中以json格式的sql值按SQL分组

时间:2018-08-21 14:35:08

标签: sql postgresql

我的表格中有以下数据

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 it self中

1 个答案:

答案 0 :(得分:2)

奇怪但可行。

警告输出是一个奇怪的伪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;