1. 程式人生 > 實用技巧 >sql列轉行

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

結果: