当前位置: 代码网 > it编程>数据库>MsSqlserver > SQL 将一列拆分成多列的实现示例

SQL 将一列拆分成多列的实现示例

2024年05月19日 MsSqlserver 我要评论
数据库中有业务表t1和字典表dictionaryt1表: dictionary表: 需求一:将col列拆分成三列sql 代码如下所示:方法一:select col,a[1] a1,a

数据库中有业务表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 一列拆分成多列内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网! 

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com