列转行SQL语句:
生成序列表步骤
1)、create table tb_sequence(id int auto_increment not null, primary key(id))
2)、insert into tb_sequence values(),(),(),(),(),(),(),(),(),();
利用序列表处理列转换行的数据
行转列sql
mysql 行转列
行转列语法
使用序列化表的方法实现行转列
select user_name, replace(substring(), char_length()) as mobile
from tb_sequence a
cross join(
select user_name, concat(mobile, ',') as mobile, length(mobile)-length(replace(mobile, ',', ''))+1 size
from user1 b
)b on a.id<b.size
列转行
select user_name,replace(substring(substring_index(mobile,','a.id),char_length(substring_index(mobile,',',a.id-1))+1),',','') as mobile from tb_sequence as a cross join( select user_name,concat(mobile,',') as mobile,length(mobile)-length(replace(mobile,',',''))+1 as size from user1 as b) as b on a.id<=b.size
建立序列表
create table tb_sequence(id int auto_increment not null,primary key(id))
insert into tb_sequence values(),(),(),(),(),(),(),(),(),(),();
行转列数据处理sql语句
序列表中初始化数据
create table tb_sequence(id int auto_increment not null,primary key(id))
给自增列中初始化数据(数据多少,取决于()的多少)
insert to tb_sequence values (),(),(),(),(),();
利用序列表处理列转行的数据
行列转换
一列转多行
列转行,唐僧 12,23,23,2转成唐僧 12 唐僧23:
列转行
select user_name,replace(substring(substring_index(mobile,','a.id),char_length(substring_index(mobile,',',a.id-1))+1),',','') as mobile from tb_sequence as a cross join( select user_name,concat(mobile,',') as mobile,length(mobile)-length(replace(mobile,',',''))+1 as size from user1 as b) as b on a.id<=b.size
利用序列化表处理列转行
创建一张序列化表并插入(行转列)
alter table user1 add column mobile varchar(100)
@MySQL---利用序列表转行的数据
SELECT user_name, REPLACE(SUBSTRING(SUBSTRING_INDEX(mobile,',',a.id),CHAR_LENGTH(SUBSTRING_INDEX(mobile,',',a.id-1))+1),',','') AS mobile FROM tb_sequence a CROSS JOIN(SELECT user_name,CONCAT(mobile,',') AS mobile, LENGTH(mobile)-LENGTH(REPLACE(mobile,',',''))+1 size FROM user1 b) b ON a.id<=b.size;