从PostgreSQL中的json列解包数据
我有一个属性表,其中一个包含11个数字元素的json数组。我需要对json数组中的数据进行一些聚合(没什么特别的,只是平均值、最大/最小统计数据等) 找到的通用答案看起来非常适合将数据重新格式化为临时视图以进行快速查询。我将jsonb_each更改为son_each(也许这会起作用?),并没有返回任何错误,但最终得到一个标题为“create_jsonb_pivot_view”的列,没有任何数据 以下是函数:从PostgreSQL中的json列解包数据,json,postgresql,Json,Postgresql,我有一个属性表,其中一个包含11个数字元素的json数组。我需要对json数组中的数据进行一些聚合(没什么特别的,只是平均值、最大/最小统计数据等) 找到的通用答案看起来非常适合将数据重新格式化为临时视图以进行快速查询。我将jsonb_each更改为son_each(也许这会起作用?),并没有返回任何错误,但最终得到一个标题为“create_jsonb_pivot_view”的列,没有任何数据 以下是函数: create or replace function create_jsonb_pivo
create or replace function create_jsonb_pivot_view
(table_name text, regular_columns text, json_column text)
returns void language plpgsql as $$
declare
s text;
begin
execute format ($fmt$
select string_agg(format('%s->>''%s'' "%s"', key, key), ',')
from (
select distinct key
from %s, json_each(%s)
order by 1
) s;
$fmt$, json_column, '%s', '%s', table_name, json_column)
into s;
execute format('
drop view if exists %s_view;
create view %s_view as
select %s, %s from %s',
table_name, table_name, regular_columns, s, table_name);
end $$;
select create_jsonb_pivot_view('table', 'A, B, C, D', 'params')
最后是使用该函数的查询:
create or replace function create_jsonb_pivot_view
(table_name text, regular_columns text, json_column text)
returns void language plpgsql as $$
declare
s text;
begin
execute format ($fmt$
select string_agg(format('%s->>''%s'' "%s"', key, key), ',')
from (
select distinct key
from %s, json_each(%s)
order by 1
) s;
$fmt$, json_column, '%s', '%s', table_name, json_column)
into s;
execute format('
drop view if exists %s_view;
create view %s_view as
select %s, %s from %s',
table_name, table_name, regular_columns, s, table_name);
end $$;
select create_jsonb_pivot_view('table', 'A, B, C, D', 'params')
我以前从未在SQL中使用过函数,所以这对我来说是一个新领域。也许有一种不同的更好的方法可以一起实现我的目标?不用管它是否真的有效——只是花了一段时间来处理函数。本打算删除我的帖子,但如果这对其他人有帮助,我会离开它 不要紧,它确实起作用了——只是花了一段时间来处理函数。本打算删除我的帖子,但如果这对其他人有帮助,我会离开它