时间:2021-07-01 10:21:17 帮助过:20人阅读
-- ------------------------------ Table structure for `t_subject`-- ----------------------------DROP TABLE IF EXISTS `t_subject`;CREATE TABLE `t_subject` ( `id` int(11) NOT NULL DEFAULT '0', `name` varchar(255) DEFAULT NULL, `subject` varchar(255) DEFAULT NULL, `results` int(11) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------ Records of t_subject-- ----------------------------INSERT INTO `t_subject` VALUES ('1', '小明', '语文', '50');INSERT INTO `t_subject` VALUES ('2', '小明', '数学', '20');INSERT INTO `t_subject` VALUES ('3', '小乐', '英语', '122');INSERT INTO `t_subject` VALUES ('4', '小乐', '语文', '500');INSERT INTO `t_subject` VALUES ('5', '小二', '数学', '100');
有一张表,表中包含一个三个人有三个科目。
SELECT t.name , SUM( IF ( t.subject = '语文', t.results, 0 ) ) AS '语文', SUM( IF ( t.subject = '数学', t.results, 0 ) ) as '数学', SUM( IF ( t.subject = '英语', t.results, 0 ) ) as '英语'FROM t_subject tGROUP BY (t.name);
执行结果如下:
当时很好奇为什么需要加SUM函数进行求和,去掉之后执行SQL如下
初步分析如果不加此函数SQL执行默认只会对进行分组后的数据进行统计
SELECT *FROM t_subject tGROUP BY t.name;