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();