sql - 在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 它自己
解决方案
奇怪但可能。
警告输出是一个奇怪的伪 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;
推荐阅读
- c# - Task.WhenAll() 包含大量任务
- nlp - 如何使 spacy 规则库仅匹配给定模式之间的内容
- ruby-on-rails - 以 Rails 多步骤形式管理时区
- r - 我如何有一个在 r 中乘以 2 个函数的函数?
- wordpress - 仅在 all_items 中显示某些自定义帖子
- python - 列表中的无效语法
- node.js - 如何对模型方法中内置的风帆进行单元测试?
- reactjs - react.js 覆盖不起作用 - 仅显示父对象
- java - 带有 oracle 合并/upsert 的 Java 准备好的语句 - 索引处缺少 IN 或 OUT 参数
- database - 使用数据库服务名称使用 keycloak 配置数据库