当前位置: 首页 > news >正文

pgsql行列转换

目录

一、造测试数据

二、行转列

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
;

执行结果

相关文章:

  • 大数据学习(56)-Impala
  • 初次使用 IDE 搭配 Lombok 注解的配置
  • kafka配置
  • 迷你世界脚本文字板接口:Graphics
  • 掌握 Python 高级特性:深入理解迭代器与生成器
  • 城市地质安全专题连载⑧ | 强化工程地质安全保障力度,为工程项目全栈护航
  • 【Aioredis实战总结】如何修改aioredis的最大连接数。
  • 带你从入门到精通——自然语言处理(五. Transformer中的自注意力机制和输入部分)
  • 泛型存储,在需求不稳定的中小型项目里,多用JSON作为存储类型可以带来哪些收益
  • perl初试
  • 网络服务之SSH协议
  • 【计算机视觉】手势识别
  • DeepSeek R1大语言模型实战工作坊02:deepseek发展演进
  • linux nginx 安装后,发现SSL模块未安装,如何处理?
  • AGI 之 【Dify】 之 使用 Docker 在 Windows 端本地部署 Dify 大语言模型(LLM)应用开发平台
  • 基于物联网技术的电动车防盗系统设计(论文+源码)
  • 【星云 Orbit • STM32F4】07. 用判断数据尾来接收据的串口通用程序框架
  • linux服务器根据内核架构下载各种软件依赖插件(例子:Anolis服务器ARM64架构内核Nginx依赖插件下载)
  • golang反射
  • cenos7网络安全检查
  • 国内外优秀网站设计/下载百度2023最新版
  • 网站建设流程哪家好/seo免费优化
  • 株洲新闻网红网株洲站/google搜索引擎入口下载
  • 网站建设与管理实验心得/教你如何建立网站
  • 企业展厅设计理念/seo专员是做什么的
  • 外贸网站怎么做优化/博客网