栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

具有基于单列数据的动态标头的MySQL数据透视表

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

具有基于单列数据的动态标头的MySQL数据透视表

看看这个类似的线程,我在其中写了一个sp以完成任务

将两个表(具有1-M关系)联接在一起,其中第二个表需要“展平”到一行

编辑。 更新的答案

create table `pivot` (  `id` int(11) not null auto_increment,  `categoryid` int(11) default null,  `processdate` date default null,  `percentchange` int(11) default null,  primary key (`id`)) engine=myisam auto_increment=9 default charset=latin1;insert  into `pivot`(`id`,`categoryid`,`processdate`,`percentchange`) values (1,4,'2011-05-10',1);insert  into `pivot`(`id`,`categoryid`,`processdate`,`percentchange`) values (2,4,'2011-05-11',22);insert  into `pivot`(`id`,`categoryid`,`processdate`,`percentchange`) values (3,4,'2011-05-12',3);insert  into `pivot`(`id`,`categoryid`,`processdate`,`percentchange`) values (4,7,'2011-05-10',4);insert  into `pivot`(`id`,`categoryid`,`processdate`,`percentchange`) values (5,7,'2011-05-11',5);insert  into `pivot`(`id`,`categoryid`,`processdate`,`percentchange`) values (6,12,'2011-05-10',6);insert  into `pivot`(`id`,`categoryid`,`processdate`,`percentchange`) values (7,12,'2011-05-12',7);insert  into `pivot`(`id`,`categoryid`,`processdate`,`percentchange`) values (8,4,'2011-05-13',12);delimiter //drop procedure if exists dynamic_view2//create procedure dynamic_view2(in sdate date,in edate date)begindeclare finish int default 0;declare cdate date;declare str varchar(10000) default "select categoryid,";declare curs cursor for select processdate from pivot where processdate between sdate and edate group by processdate;declare continue handler for not found set finish = 1;open curs;my_loop:loopfetch curs into cdate;if finish = 1 thenleave my_loop;end if;set str = concat(str, "max(case when processdate = '",cdate,"' then percentchange else null end) as `",cdate,"`,");end loop;close curs;set str = substr(str,1,char_length(str)-1);set @str = concat(str," from pivot group by categoryid");prepare stmt from @str;execute stmt;deallocate prepare stmt;end;//delimiter ;mysql> call dynamic_view2('2011-05-10','2011-05-13');+------------+------------+------------+------------+------------+| categoryid | 2011-05-10 | 2011-05-11 | 2011-05-12 | 2011-05-13 |+------------+------------+------------+------------+------------+|          4 |          1 |         22 |          3 |         12 ||          7 |          4 |          5 |       NULL |       NULL ||         12 |          6 |       NULL |          7 |       NULL |+------------+------------+------------+------------+------------+3 rows in set (0.00 sec)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/416719.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号