MySQL实现将行转列的技巧(mysql行转列)

数据库在实际开发中,经常会有很多的处理操作,其中就有行转列的功能,行转列操作实现的原理是将某列转换成多个列,通过多个列来明确一条数据。MySQL实现行转列技巧有如下几种:

1. 使用UNION ALL加上累加值来实现行转列

首先要有一个框架,也就是将列按行划分,那么可以累加行号r,累加可以使用row_number()函数实现,然后再使用case when排序,通过case when来实现在列上循环,我们把数据按行排列,然后一行三列,得不到什么到结果我们可以使另一个查询,让每行一列,用union all实现行转列,并且再case when后面加入累加值即可。例如如下代码:

select 
case when r%3=1 then value end as '列1' ,
case when r%3=2 then value end as '列2' ,
case when r%3=0 then value end as '列3'
from table
where ...
order by ...
union all
select
case when r%3=1 then value end,
case when r%3=2 then value end,
case when r%3=0 then value end
from table
where ...
order by ...

2. 使用GROUP_CONCAT函数实现行转列

group_concat函数可以实现将多个数据拼接到一起,可以帮助我们实现行转列,具体实现原理如下:

SELECT 
table_name,
GROUP_CONCAT(column_name SEPARATOR '|')
FROM table
GROUP BY table_name;

感谢分享


数据运维技术 » MySQL实现将行转列的技巧(mysql行转列)