PostgreSQL 行列轉換的實現(xiàn)方法
一、造測試數(shù)據(jù)
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;造完數(shù)據(jù)如下

二、行轉列
1.函數(shù)定義
regexp_split_to_table是PostgreSQL中的一個函數(shù),用于將一個字符串根據(jù)正則表達式進行分割,并將結果返回為一個表格,每個分割后的部分作為一行。
2.語法
regexp_split_to_table(string text, pattern text) → setof text string:要分割的原始字符串。 pattern:用于分割的正則表達式模式? 返回值,該函數(shù)返回一個setof text,即一個文本類型的行集合,包含所有分割后的部分
3.示例
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
;執(zhí)行結果

三、列轉行
1.函數(shù)定義
string_agg() 函數(shù)是 PostgreSQL 中的一個聚合函數(shù),用于將一個列中的值連接成一個字符串。
2.語法
string_agg(column_name, separator) column_name:要聚合的列名。 separator:可選參數(shù),用于連接各個值的分隔符。如果未指定或為空,則使用默認分隔符(逗號加空格)。
3.示例
--將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
;執(zhí)行結果

--根據(jù)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
;執(zhí)行結果

到此這篇關于pgsql行列轉換的實現(xiàn)方法的文章就介紹到這了,更多相關pgsql行列轉換內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
PostgreSQL數(shù)據(jù)庫中to_timestamp函數(shù)用法示例
PostgreSQL 的 to_timestamp 函數(shù)可以將字符串或整數(shù)轉換為時間戳,這篇文章主要介紹了PostgreSQL數(shù)據(jù)庫中to_timestamp函數(shù)用法的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2025-08-08
PostgreSQL數(shù)據(jù)庫管理系統(tǒng)快速入門
這篇文章主要介紹了PostgreSQL數(shù)據(jù)庫快速入門,PostgreSQL是一個功能強大的開源對象關系型數(shù)據(jù)庫系統(tǒng),他使用和擴展了SQL語言,并結合了許多安全存儲和擴展最復雜數(shù)據(jù)工作負載的功能,需要的朋友可以參考下2023-07-07

