MySQL 的 列转行 小示例

    技术2023-08-03  68

    不管我们在平时的学习或工作中,难免会遇到列转行的数据操作,比如下面的这个例子:

    1、先建立我们的测试表

    drop table if exists stu_Score; create table stu_Score(name varchar(10),Java int,`C#` int,Python int);

    2、插入测试数据

    insert into stu_Score values('Dina',82,93,90); insert into stu_Score values('Paradox',87,80,95); insert into stu_Score values('Augenstern',93,86,90);;

    3、看一下测试数据

    4、实现列转行

    select * from( select name,'Java' as course,Java as score from stu_Score union all select name,'C#' as course,`C#` as score from stu_Score union all select name,'Python' as course,Python as score from stu_Score)stu_Info -- name 按Dina、Paradox 、Augenstern 的顺序输出 order by (case when name = 'Dina' then 1 when name = 'Paradox' then 2 when name = 'Augenstern' then 3 end), -- course 按 Java、C#、Python 的顺序输出 (case when course = 'Java' then 1 when course = 'C#' then 2 when course = 'Python' then 3 end);

    5、执行代码,可实现:

    希望对你有帮助!!! 

    若想了解 MySQL 的行转列实现小示例,可点击 此处

    若想了解 MySQL 的行转列 与 列转行 的应用小示例,可点击 此处

    Processed: 0.010, SQL: 10