SQL语句 实现数据库表中的行转列查询
程序员文章站
2022-05-09 23:43:44
...
- 首先需要创建一张表比如:
- 下面是建表和表数据的SQL语句:新建一个tb.txt文本文件,把下面的SQL语句复制,然后把文件后缀更改为.sql;然后到数据库运行:
/*
Navicat Premium Data Transfer
Source Server : localhost
Source Server Type : MySQL
Source Server Version : 80015
Source Host : localhost:3306
Source Schema : infostat
Target Server Type : MySQL
Target Server Version : 80015
File Encoding : 65001
Date: 02/05/2020 21:15:07
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for tb
-- ----------------------------
DROP TABLE IF EXISTS `tb`;
CREATE TABLE `tb` (
`name` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`sub` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`result` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of tb
-- ----------------------------
INSERT INTO `tb` VALUES ('张三', '语文', '98');
INSERT INTO `tb` VALUES ('张三', '数学', '114');
INSERT INTO `tb` VALUES ('李四', '语文', '102');
INSERT INTO `tb` VALUES ('李四', '数学', '108');
INSERT INTO `tb` VALUES ('王五', '语文', '112');
INSERT INTO `tb` VALUES ('王五', '数学', '118');
INSERT INTO `tb` VALUES ('张三', '物理', '101');
INSERT INTO `tb` VALUES ('李四', '物理', '98');
INSERT INTO `tb` VALUES ('王五', '物理', '88');
SET FOREIGN_KEY_CHECKS = 1;
- 运行数据库文件:
- 具体的SQL语句:
select `Name` as 姓名 ,
max(case Sub when '语文' then Result else 0 end) 语文,
max(case Sub when '数学' then Result else 0 end) 数学,
max(case Sub when '物理' then Result else 0 end) 物理
from tb
group by `Name`
- 运行结果:
上一篇: 数据库 SQL 语句练习
下一篇: java从mysql导出数据例子