[SQL智慧航行者] - 行转列1

话不多说, 先看数据表信息.

数据表信息:

假设 A B C 三位小朋友期末考试成绩如下所示:

+-----+-----------+------|
| name|   subject |score |
+-----+-----------+------|
|  A  |  chinese  |  99  |
|  A  |  math     |  98  |
|  A  |  english  |  97  |
|  B  |  chinese  |  92  |
|  B  |  math     |  91  |
|  B  |  english  |  90  |
|  C  |  chinese  |  88  |
|  C  |  math     |  87  |
|  C  |  english  |  86  |
+-----+-----------+------|

话不多说, 再看需求~

需求:

请使用 SQL 代码将以上成绩转换为如下格式:

+-----+-----------+------|---------|
| name|   chinese | math | english |
+-----+-----------+------|---------|
|  A  |     99    |  98  |    97   |
|  B  |     92    |  91  |    90   |
|  C  |     88    |  87  |    86   |
+-----+-----------+------|---------|

话不多说, 进行拆解~

拆解:

select 
    name,
    max(case when subject = 'chinese' then score end) as chinese,
    max(case when subject = 'math' then score end) as math,
    max(case when subject = 'english' then score end) as english
from
    stu_score
group by
    name;

效果如下:
[SQL智慧航行者] - 行转列1_第1张图片

最后给大家介绍一下我这边的创建数据表和插入数据的操作步骤, 想要自己测试的话, 可以参考:

CREATE TABLE stu_score (
    name VARCHAR(10),
    subject VARCHAR(10),
    score INT
);

INSERT INTO stu_score (name, subject, score)
VALUES ('A', 'chinese', 99),
       ('A', 'math', 98),
       ('A', 'english', 97),
       ('B', 'chinese', 92),
       ('B', 'math', 91),
       ('B', 'english', 90),
       ('C', 'chinese', 88),
       ('C', 'math', 87),
       ('C', 'english', 86);

效果如下:
[SQL智慧航行者] - 行转列1_第2张图片

你可能感兴趣的:(#,SQL刷题,sql,数据库,mysql,数据仓库,大数据)