目錄
一、造測試數據
二、行轉列
1.函數定義
2.語法
3.示例
三、列轉行
1.函數定義
2.語法
3.示例
一、造測試數據
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;
造完數據如下?
二、行轉列
1.函數定義
?regexp_split_to_table是PostgreSQL中的一個函數,用于將一個字符串根據正則表達式進行分割,并將結果返回為一個表格,每個分割后的部分作為一行??。
2.語法
regexp_split_to_table(string text, pattern text) → setof text
string:要分割的原始字符串。
pattern:用于分割的正則表達式模式?返回值,該函數返回一個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
;
執行結果
三、列轉行
1.函數定義
string_agg() 函數是 PostgreSQL 中的一個聚合函數,用于將一個列中的值連接成一個字符串。
2.語法
string_agg(column_name, separator) ?column_name:要聚合的列名。
separator:可選參數,用于連接各個值的分隔符。如果未指定或為空,則使用默認分隔符(逗號加空格)。
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
;
執行結果
--根據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
;
執行結果