最近公司系统在做改造,数据库产品也换了,由Oracle数据库换成postgresql 数据库。
在开发的过程中,同事遇到一问题,就是有张表有个字段的数据存储格式是
A|B|C 这种形式, 现在要专业这种形式 钻石|铂金|黄金。
A对应的是钻石
B对应的是铂金
C对应的是黄金
刚开始以为要自定义一个函数,实现这样一个转换功能,偶然在qq群看到 pg有 regexp_split_to_table 函数。于是看是做实验测试:
--建表
drop table if exists test1;
drop table if exists test2;
create table test1(tier_code varchar(100));
create table test2(tier_code varchar(100),tier_name varchar(100));
复制
--测试数据
insert into test1(tier_code) values ('A|B');
insert into test1(tier_code) values('A|B|C');
insert into test1(tier_code) values('A|B|C|E');
复制
insert into test2(tier_code,tier_name) values('A','钻石');
insert into test2(tier_code,tier_name) values('B','铂金');
insert into test2(tier_code,tier_name) values('C','黄金');
insert into test2(tier_code,tier_name) values('E','黑钻');
复制
--查询表的数据
select * from test1;
select * from test2;
复制
--最终查询sql
select t.tier_code, string_agg(t.tier_name, '|')
from (select t.tier_code,
t.tier_code_2,
(select t2.tier_name
from test2 t2
where t2.tier_code = t.tier_code_2) tier_name
from (select t.tier_code,
regexp_split_to_table(tier_code2, ',') tier_code_2
from (select tier_code,
replace(tier_code, '|', ',') tier_code2
from test1) t) t) t
group by t.tier_code;
复制
查询结果:
tier_code | string_agg |
A|B|C|E | 钻石|铂金|黄金|黑钻 |
A|B | 钻石|铂金 |
A|B|C | 钻石|铂金|黄金 |
总结:
上面最终查询sql用到了3个函数,replace函数,将tier_code中的竖线|替换成逗号,;
其实用到了炸裂函数regexp_split_to_table,将一个字段的值根据逗号分隔符拆成一个结果集;
最后用到了string_agg函数把一个结果集合并成一个字符串
今天
文章转载自朱清伟的学习笔记,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。
评论
相关阅读
外国CTO也感兴趣的开源数据库项目——openHalo
小满未满、
1839次阅读
2025-04-21 16:58:09
3月“墨力原创作者计划”获奖名单公布
墨天轮编辑部
381次阅读
2025-04-15 14:48:05
转发有奖 | PostgreSQL 16 PGCM高级认证课程直播班招生中!
墨天轮小教习
194次阅读
2025-04-14 15:58:34
中国PostgreSQL培训认证体系新增PGAI应用工程师方向
开源软件联盟PostgreSQL分会
189次阅读
2025-05-06 10:21:13
华象新闻 | PostgreSQL 18 Beta 1、17.5、16.9、15.13、14.18、13.21 发布
严少安
163次阅读
2025-05-09 11:34:10
PG生态赢得资本市场青睐:Databricks收购Neon,Supabase融资两亿美元,微软财报点名PG
老冯云数
148次阅读
2025-05-07 10:06:22
SQL 优化之 OR 子句改写
xiongcc
143次阅读
2025-04-21 00:08:06
告别老旧mysql_fdw,升级正当时
NickYoung
126次阅读
2025-04-29 11:15:18
PostgreSQL中文社区亮相于第八届数字中国峰会
PostgreSQL中文社区
114次阅读
2025-05-07 10:06:20
PostgreSQL的dblink扩展模块使用方法
szrsu
109次阅读
2025-04-24 17:39:30