欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PostgreSQL 行列轉(zhuǎn)換的實(shí)現(xiàn)方法

 更新時間:2025年07月30日 09:32:56   作者:chimchim66  
本文主要介紹了PostgreSQL 行列轉(zhuǎn)換的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

一、造測試數(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ù)如下 

二、行轉(zhuǎn)列

1.函數(shù)定義

‌regexp_split_to_table是PostgreSQL中的一個函數(shù),用于將一個字符串根據(jù)正則表達(dá)式進(jìn)行分割,并將結(jié)果返回為一個表格,每個分割后的部分作為一行‌‌。

2.語法

regexp_split_to_table(string text, pattern text) → setof text
string:要分割的原始字符串。
pattern:用于分割的正則表達(dá)式模式?

返回值,該函數(shù)返回一個setof text,即一個文本類型的行集合,包含所有分割后的部分

3.示例

select 
     id
    ,json1 
    ,json2 
    ,regexp_replace(regexp_replace(json2,'{',''),'}','') no_json2 --剔除json2外面大括號
    ,regexp_split_to_table(json1,',') as j1 --使用json1來轉(zhuǎn)換結(jié)果
    ,regexp_split_to_table(regexp_replace(regexp_replace(json2,'{',''),'}',''),',') as j2 --使用json2來轉(zhuǎn)換結(jié)果
from test 
;

執(zhí)行結(jié)果

三、列轉(zhuǎn)行

1.函數(shù)定義

string_agg() 函數(shù)是 PostgreSQL 中的一個聚合函數(shù),用于將一個列中的值連接成一個字符串。

2.語法

string_agg(column_name, separator)  

column_name:要聚合的列名。
separator:可選參數(shù),用于連接各個值的分隔符。如果未指定或?yàn)榭?,則使用默認(rèn)分隔符(逗號加空格)。

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來轉(zhuǎn)換結(jié)果
    ,regexp_split_to_table(regexp_replace(regexp_replace(json2,'{',''),'}',''),',') as j2 --使用json2來轉(zhuǎn)換結(jié)果
from test 
) t 
;

執(zhí)行結(jié)果

--根據(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來轉(zhuǎn)換結(jié)果
    ,regexp_split_to_table(regexp_replace(regexp_replace(json2,'{',''),'}',''),',') as j2 --使用json2來轉(zhuǎn)換結(jié)果
from test 
) t 
group by id
;

執(zhí)行結(jié)果

到此這篇關(guān)于pgsql行列轉(zhuǎn)換的實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)pgsql行列轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

最新評論