Home  >  Article  >  Database  >  MYSQL 横向展示数据_MySQL

MYSQL 横向展示数据_MySQL

WBOY
WBOYOriginal
2016-06-01 13:11:311749browse

最近准备面试题,想之前面试过一家公司时遇到一个SQL题,横向展示一个表中数据,当时没写出现写下总结,以免忘记。

-- ------------------------------ 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);

   执行结果如下:

MYSQL 横向展示数据_MySQL

   当时很好奇为什么需要加SUM函数进行求和,去掉之后执行SQL如下

MYSQL 横向展示数据_MySQL

 初步分析如果不加此函数SQL执行默认只会对进行分组后的数据进行统计

SELECT	*FROM	t_subject tGROUP BY t.name;

MYSQL 横向展示数据_MySQL

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn