一、一個學生成績表sql
DROP TABLE IF EXISTS `tb_grade`; CREATE TABLE `tb_grade` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(32) DEFAULT NULL, `subject_type` int(1) unsigned DEFAULT NULL, `grade` int(2) unsigned DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of tb_grade -- ---------------------------- INSERT INTO `tb_grade` VALUES ('1', 'zhangsan', '1', '100'); INSERT INTO `tb_grade` VALUES ('2', 'zhangsan', '2', '89'); INSERT INTO `tb_grade` VALUES ('3', 'zhangsan', '3', '100'); INSERT INTO `tb_grade` VALUES ('4', 'lisi', '1', '90'); INSERT INTO `tb_grade` VALUES ('5', 'lisi', '2', '100'); INSERT INTO `tb_grade` VALUES ('6', 'wangwu', '1', '78'); INSERT INTO `tb_grade` VALUES ('7', 'wangwu', '2', '49'); INSERT INTO `tb_grade` VALUES ('8', 'wangwu', '3', '76');
二、查詢每一個學生的成績彙總code
/*方式一:*/ SELECT username, GROUP_CONCAT(grade) FROM tb_grade GROUP BY username; /*方式二*/ SELECT username, SUM(CASE subject_type WHEN 1 THEN grade ELSE 0 END) AS '數學', SUM(CASE subject_type WHEN 2 THEN grade ELSE 0 END) AS '語文', SUM(CASE subject_type WHEN 3 THEN grade ELSE 0 END) AS '英語' FROM tb_grade GROUP BY username;