“SQL行列转换”的版本间的差异

来自姬鸿昌的知识库
跳到导航 跳到搜索
第60行: 第60行:
 
|82
 
|82
 
|}
 
|}
 +
 +
==== 建表 ====
 
<syntaxhighlight lang="sql">
 
<syntaxhighlight lang="sql">
 
CREATE TABLE `score` (
 
CREATE TABLE `score` (
第66行: 第68行:
 
   `grade` int(11) DEFAULT NULL
 
   `grade` int(11) DEFAULT NULL
 
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
 
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
 +
</syntaxhighlight>
  
 +
 +
 +
==== 插入测试数据 ====
 +
<syntaxhighlight lang="sql">
 
INSERT INTO `sql`.`score`
 
INSERT INTO `sql`.`score`
 
(`sname`,`cname`,`grade`)
 
(`sname`,`cname`,`grade`)
第80行: 第87行:
 
('王五','英语',82);
 
('王五','英语',82);
 
</syntaxhighlight><syntaxhighlight lang="sql">
 
</syntaxhighlight><syntaxhighlight lang="sql">
 +
/*非语文科目显示为0*/
 +
select sname as "姓名",
 +
case cname when '语文' then grade else 0 end as "语文"
 +
from score;
 +
</syntaxhighlight>
 +
{| class="wikitable"
 +
|张三
 +
|80
 +
|-
 +
|李四
 +
|77
 +
|-
 +
|王五
 +
|91
 +
|-
 +
|张三
 +
|0
 +
|-
 +
|李四
 +
|0
 +
|-
 +
|王五
 +
|0
 +
|-
 +
|张三
 +
|0
 +
|-
 +
|李四
 +
|0
 +
|-
 +
|王五
 +
|0
 +
|}
 +
<syntaxhighlight lang="sql">
 
/*非语文科目显示为0*/
 
/*非语文科目显示为0*/
 
select sname as "姓名",
 
select sname as "姓名",

2022年11月11日 (五) 06:40的版本

https://www.bilibili.com/video/BV1MF411z7X9

问题描述

学生成绩记录表包含以下信息:

sname cname grade
张三 语文 80
李四 语文 77
王五 语文 91
张三 数学 85
李四 数学 90
王五 数学 60
…… …… ……


要求以每个学生一行数据的形式创建以下报表:

姓名 语文 数学 英语
张三 80 85 81
李四 77 90 69
王五 91 60 82

建表

CREATE TABLE `score` (
  `sname` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `cname` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `grade` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


插入测试数据

INSERT INTO `sql`.`score`
(`sname`,`cname`,`grade`)
VALUES
('张三','语文',80),
('李四','语文',77),
('王五','语文',91),
('张三','数学',85),
('李四','数学',90),
('王五','数学',60),
('张三','英语',81),
('李四','英语',69),
('王五','英语',82);
/*非语文科目显示为0*/
select sname as "姓名",
case cname when '语文' then grade else 0 end as "语文"
from score;
张三 80
李四 77
王五 91
张三 0
李四 0
王五 0
张三 0
李四 0
王五 0
/*非语文科目显示为0*/
select sname as "姓名",
case cname when '语文' then grade else 0 end as "语文"
from score;

/*非语文科目列为NULL*/
select sname as "姓名",
case cname when '语文' then grade end as "语文"
from score;