zoukankan      html  css  js  c++  java
  • sql列转行

    建表语句:

    SET FOREIGN_KEY_CHECKS=0;
    
    -- ----------------------------
    -- Table structure for studentscores
    -- ----------------------------
    DROP TABLE IF EXISTS `studentscores`;
    CREATE TABLE `studentscores` (
      `UserName` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
      `Subject` varchar(30) CHARACTER SET utf8 DEFAULT NULL,
      `Score` float DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
    -- ----------------------------
    -- Records of studentscores
    -- ----------------------------
    INSERT INTO `studentscores` VALUES ('Nick', '语文', '80');
    INSERT INTO `studentscores` VALUES ('Nick', '数学', '90');
    INSERT INTO `studentscores` VALUES ('Nick', '英语', '70');
    INSERT INTO `studentscores` VALUES ('Nick', '生物', '85');
    INSERT INTO `studentscores` VALUES ('Kent', '语文', '80');
    INSERT INTO `studentscores` VALUES ('Kent', '数学', '90');
    INSERT INTO `studentscores` VALUES ('Kent', '英语', '70');
    INSERT INTO `studentscores` VALUES ('Kent', '生物', '85');

    表数据:  

     列转行:

    select 
          username, 
          max(case subject when '语文' then score else 0 end) as '语文',
          max(case subject when '数学' then score else 0 end) as '数学',
          max(case subject when '英语' then score else 0 end) as '英语',
          max(case subject when '生物' then score else 0 end) as '生物'
    from studentscores
    group by username

    结果:  

  • 相关阅读:
    查询计划Hash和查询Hash
    执行计划的重用
    执行计划组件、组件、老化
    执行计划的生成
    查询反模式
    T-SQL 公用表表达式(CTE)
    SQL 操作结果集 -并集、差集、交集、结果集排序
    SQL语句
    POJ 1821 单调队列+dp
    区间gcd问题 HDU 5869 离线+树状数组
  • 原文地址:https://www.cnblogs.com/Mike_Chang/p/13928775.html
Copyright © 2011-2022 走看看