数据库中有业务表t1和字典表dictionary
t1表:
dictionary表:
需求一:将col列拆分成三列
sql 代码如下所示:
方法一:
select col,a[1] a1,a[2] a2,a[3] a3 from ( select regexp_split_to_array( col, ',' ), col from t1 ) as dt (a)
效果:
方法二:
select col, split_part( col, ',', 1 ) a1, split_part( col, ',', 2 ) a2, split_part( col, ',', 3 ) a3 from t1
效果:
假设想把 "col" 列分成 "col1" 、 "col2"、 "col3",sql语句:
1、先添加新的列
alter table t1 add column col1 varchar(30); alter table t1 add column col2 varchar(30); alter table t1 add column col3 varchar(30);
2、再用 split_part
函数填充新的列
update t1 set col1 = split_part( col, ',', 1 ), col2 = split_part( col, ',', 2 ), col3 = split_part( col, ',', 3 );
效果:
需求二:列col保存的数据,是字典表dictionary中id值拼接的字符串,想关联出对应 的name值。
sql 代码如下所示:
select col, (select name from dictionary where id=a[1]) a1, (select name from dictionary where id=a[2]) a2, (select name from dictionary where id=a[3]) a3 from ( select regexp_split_to_array( col, ',' ), col from t1 ) as dt (a)
效果:
需求三:列col转化为字典表dictionary中name拼接的字符串
sql 代码如下所示:
select col,concat_ws(',',a1,a2,a3) as names from ( select col, (select name from dictionary where id=a[1]) a1, (select name from dictionary where id=a[2]) a2, (select name from dictionary where id=a[3]) a3 from ( select regexp_split_to_array( col, ',' ), col from t1 ) as dt (a) ) as temp
效果:
总结 :
我们可能会遇到按分隔符拆成多行或者多列的情况,以及复制的业务需求,只需视情况调整sql语句,或者编写存储过程。
对于列col的值,按分隔符拆分为多列数据时,不知道需要拆分成几列,可以先用以下sql查询出列数。
select max(array_length(regexp_split_to_array(col,','),1))
到此这篇关于sql 将一列拆分成多列的实现示例的文章就介绍到这了,更多相关sql 一列拆分成多列内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论