MySQL 行列相互转换

Posted 泥泥呀的学习笔记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL 行列相互转换相关的知识,希望对你有一定的参考价值。

行列相互转换

/*创建表*/
CREATE TABLE ic (
    NAME VARCHAR (20),
    Product VARCHAR (20),
    amount INT
);
INSERT INTO ic
VALUES
    (\'王一\', \'A1\', 20),
    (\'王一\', \'A3\', 150),
    (\'王一\', \'A2\', 10),
    (\'赵二\', \'A1\', 52),
    (\'赵二\', \'A2\',46),
    (\'赵二\', \'A3\',78),
    (\'刘六\', \'A1\',55),
    (\'刘六\', \'A2\',20),
    (\'刘六\', \'A3\',86);

SELECT * FROM ic;

想要用product列的值做列,列名变为 name,A1,A2,A3。

CREATE TABLE ic_1
SELECT name ,
SUM(IF(Product=\'A1\',amount,0)) AS A1,
SUM(IF(Product=\'A2\',amount,0)) AS A2,
SUM(IF(Product=\'A3\',amount,0)) AS A3
FROM ic
GROUP BY name;

 

 如果将ic_1表再变回到原来的样子

SELECT name, \'A1\' AS Product, A1 AS amount from ic_1
UNION
SELECT name, \'A2\' AS Product, A2 AS amount from ic_1
UNION
SELECT name, \'A3\' AS Product, A3 AS amount from ic_1
ORDER BY name;

 

 

以上是关于MySQL 行列相互转换的主要内容,如果未能解决你的问题,请参考以下文章

mysql高级查询实例:行列转换一行多行转换

转载mysql行列转换方法总结

EXCEL实现行列转换

Mysql 行列转换

sql动态实现行列转换

sql行列转换和累加问题~~~