76人参与 • 2025-07-30 • MsSqlserver
create table test (
id int,
json1 varchar,
json2 varchar
);
insert into test values(1,'111','{111}');
insert into test values(2,'111,222','{111,222}');
insert into test values(3,'111,222,333','{111,222,333}');
select * from test;造完数据如下

regexp_split_to_table是postgresql中的一个函数,用于将一个字符串根据正则表达式进行分割,并将结果返回为一个表格,每个分割后的部分作为一行。
regexp_split_to_table(string text, pattern text) → setof text string:要分割的原始字符串。 pattern:用于分割的正则表达式模式 返回值,该函数返回一个setof text,即一个文本类型的行集合,包含所有分割后的部分
select
id
,json1
,json2
,regexp_replace(regexp_replace(json2,'{',''),'}','') no_json2 --剔除json2外面大括号
,regexp_split_to_table(json1,',') as j1 --使用json1来转换结果
,regexp_split_to_table(regexp_replace(regexp_replace(json2,'{',''),'}',''),',') as j2 --使用json2来转换结果
from test
;执行结果

string_agg() 函数是 postgresql 中的一个聚合函数,用于将一个列中的值连接成一个字符串。
string_agg(column_name, separator) column_name:要聚合的列名。 separator:可选参数,用于连接各个值的分隔符。如果未指定或为空,则使用默认分隔符(逗号加空格)。
--将j1用;拼接
select string_agg (j1,';')
from (
select
id
,json1
,json2
,regexp_replace(regexp_replace(json2,'{',''),'}','') no_json2 --剔除json2外面大括号
,regexp_split_to_table(json1,',') as j1 --使用json1来转换结果
,regexp_split_to_table(regexp_replace(regexp_replace(json2,'{',''),'}',''),',') as j2 --使用json2来转换结果
from test
) t
;执行结果

--根据id分组按j1用abc拼接
select id,string_agg (j1,'abc')
from (
select
id
,json1
,json2
,regexp_replace(regexp_replace(json2,'{',''),'}','') no_json2 --剔除json2外面大括号
,regexp_split_to_table(json1,',') as j1 --使用json1来转换结果
,regexp_split_to_table(regexp_replace(regexp_replace(json2,'{',''),'}',''),',') as j2 --使用json2来转换结果
from test
) t
group by id
;执行结果

到此这篇关于pgsql行列转换的实现方法的文章就介绍到这了,更多相关pgsql行列转换内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论