zoukankan      html  css  js  c++  java
  • MySQL动态行转列

    创建源表和插入源数据

    DROP TABLE IF EXISTS `score`;
    CREATE TABLE `score` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `class` varchar(255) DEFAULT NULL,
      `score` double DEFAULT NULL,
      `userid` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;
    INSERT INTO `score` VALUES ('1', 'math', '90', '1');
    INSERT INTO `score` VALUES ('2', 'english', '90', '1');
    INSERT INTO `score` VALUES ('3', 'computer', '80', '1');
    INSERT INTO `score` VALUES ('4', 'sports', '90', '1');
    INSERT INTO `score` VALUES ('5', 'math', '80', '2');
    INSERT INTO `score` VALUES ('6', 'english', '85', '2');
    INSERT INTO `score` VALUES ('7', 'computer', '100', '2');

    原表记录

    需要查询出的结果记录

    查询语句:

    SET @EE='';
    set @str_tmp='';
    SELECT @EE:=CONCAT(@EE,'SUM(IF(class=\'',class,'\'',',score,0)) AS ',class,',') as aa into @str_tmp FROM (SELECT DISTINCT class FROM score) A order by length(aa) desc limit 1; 
    SET @QQ=CONCAT('SELECT ifnull(score.userid,\'total\'),',LEFT(@str_tmp,char_length(@str_tmp)-1),'  ,SUM(score) AS TOTAL FROM score GROUP BY userid WITH ROLLUP');
    PREPARE stmt  FROM @QQ; 
    EXECUTE stmt ;
    deallocate prepare stmt;
  • 相关阅读:
    istio-流量管理-基于不同版本访问规则控制
    k8s安装istio
    策略模式
    递归思想
    Java Lambda 表达式
    redis实现分布式锁
    MySQL 的优化方案总结
    linux下查看某一端口被哪个进程占用
    组合模式
    桥接模式
  • 原文地址:https://www.cnblogs.com/whai/p/4813465.html
Copyright © 2011-2022 走看看