MySql动态行转列

drop table if exists tuser ;
create table tuser (sname varchar(10) , imon varchar(10) ,iqty int);

insert into tuser 
select '张三','1月',8 
union all select '张三','2月',12 
union all select '李四','1月',6 
union all select '王五','1月',9 
union all select '李四','2月',14 
union all select '赵六','1月',15
union all select '李四','3月',7
union all select '赵六','2月',6 ;

DROP PROCEDURE IF EXISTS `sp_row_column_wrap`;
CREATE PROCEDURE `sp_row_column_wrap`(
    #IN $param1 varchar(10), 
    #IN $param2 varchar(10) 
)
BEGIN
    declare $stm varchar(8000);
    declare $colcount int ;
    declare $i int ;
    
    set $colcount = 0 ;
    set $i = 1;
    set $stm = 'select imon ';    
    
    select count(distinct sname) into $colcount from tuser ; 
    
    while $i<= $colcount do 
         set @i:=0 ;
         select col
         from (
             select 
                    (@i:=@i+1) as rowno,
                    CONCAT($stm,',SUM(case sname when ''',sname,''' then iqty else null end) as ''',sName,'''') as col
             from (
                      select distinct sname
                      from tuser
                      order by sname
                  ) as tb 
             ) tbl
         where rowno=$i         
         into $stm; 
         
         set $i = $i+1 ;
         
     end while;
    
    Set @stm= concat($stm,' from tuser 
    group by imon order by imon ;');

    prepare s from @stm;    
    execute s;
    deallocate prepare s;
END;

call sp_row_column_wrap();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值