目的:将指定字段横行转竖行(同key,不同参数)
建表语句:
DROP TABLE IF EXISTS `temp`; CREATE TABLE `temp` ( `id` int(11) NOT NULL AUTO_INCREMENT, `keycode` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `date` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `quantity` float(7, 2) UNSIGNED NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 2482 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
结果:
SELECT keycode ,MAX(CASE date WHEN '207' THEN quantity ELSE 0 END ) '2020-7-31' ,MAX(CASE date WHEN "208" THEN quantity ELSE 0 END ) '2020-08-31' ,MAX(CASE date WHEN '209' THEN quantity ELSE 0 END ) '2020-9-30' ,MAX(CASE date WHEN '2010' THEN quantity ELSE 0 END ) '2020-10-31' ,MAX(CASE date WHEN '2011' THEN quantity ELSE 0 END ) '2020-11-30' ,MAX(CASE date WHEN '2012' THEN quantity ELSE 0 END ) '2020-12-31' ,MAX(CASE date WHEN '2101' THEN quantity ELSE 0 END ) '2021-1-31' ,MAX(CASE date WHEN '2102' THEN quantity ELSE 0 END ) '2021-2-28' ,MAX(CASE date WHEN '2103' THEN quantity ELSE 0 END ) '2021-3-31' ,MAX(CASE date WHEN '2104' THEN quantity ELSE 0 END ) '2021-4-30' ,MAX(CASE date WHEN '2105' THEN quantity ELSE 0 END ) '2021-5-31' ,MAX(CASE date WHEN '2106' THEN quantity ELSE 0 END ) '2021-6-30' FROM temp GROUP BY keycode;
注:其中when''的值存在“-”时,输入数值不准,故改成‘207’等数字,已作区分,后面再行研究
留言评论
暂无留言