mysql中列转行

在mysql中创建一张表,名为syj;
select * from syj;数据如下:
mysql中列转行_第1张图片

要实现如下的效果:
这里写图片描述

代码如下:


select 
sum(case when rowNo%3=1 then id end) no1,
sum(case when rowNo%3=2 then id end) no2,
sum(case when rowNo%3=0 then id end) no3
from (
    select id1 as id,'t1' as t1,(@rowNo:=@rowNo+1) as rowNo from syj,(select @rowNo:=0) rw where  id1!=0 
     union
    select id2 as id,'t2' as t1,(@rowNo:=@rowNo+1) as rowNo from syj,(select @rowNo:=0) rw where  id2!=0 
     union
    select id3 as id,'t3' as t1,(@rowNo:=@rowNo+1) as rowNo from syj,(select @rowNo:=0) rw where  id3!=0 
)edc
GROUP BY t1

继续优化中。。。

你可能感兴趣的:(sql,sql)