有一个表如下:
CREATE TABLE `student` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL DEFAULT '0',
`subject` VARCHAR(50) NOT NULL DEFAULT '0',
`score` INT(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
COMMENT='测试数据'
ENGINE=InnoDB
;
数据库中已有数据如下:
INSERT INTO `student` (`id`, `name`, `subject`, `score`) VALUES (1, '张三', '语文', 80);
INSERT INTO `student` (`id`, `name`, `subject`, `score`) VALUES (2, '张三', '数学', 90);
INSERT INTO `student` (`id`, `name`, `subject`, `score`) VALUES (3, '张三', '英语', 82);
INSERT INTO `student` (`id`, `name`, `subject`, `score`) VALUES (4, '李四', '语文', 70);
INSERT INTO `student` (`id`, `name`, `subject`, `score`) VALUES (5, '李四', '数学', 85);
INSERT INTO `student` (`id`, `name`, `subject`, `score`) VALUES (6, '李四', '英语', 90);
INSERT INTO `student` (`id`, `name`, `subject`, `score`) VALUES (7, '马武', '语文', 50);
INSERT INTO `student` (`id`, `name`, `subject`, `score`) VALUES (8, '马武', '数学', 97);
交叉查询,横向显示数据如下:
select
name, sum(s.score) as sum,
(case when s.subject='语文' then s.score else null end) as 语文,
(case when s.subject='数学' then s.score else null end) as 数学,
(case when s.subject='英语' then s.score else null end) as 英语
from student s
group by name
显示:
name, 合计,语文,数学,英语
('张三', 252, 80, 90, 82);
('李四', 245, 70, 85, 90);
('马武', 147, 50, 97, NULL);