2020-09-22

MySQL 纵表转横表查询实现

纵表转横表查询实现

By:授客 QQ:1033553122 欢迎加入全国软件测试交流群:7156436

实践环境

MySQL 5.7

 

创建测试表

CREATE TABLE tb_test (

id INT AUTO_INCREMENT PRIMARY KEY,

attr VARCHAR (20),

attr_value VARCHAR (20)

) ;

 

插入测试数据

INSERT INTO tb_test(attr, attr_value) VALUES('age', 18), ('sex', '男'), ('name', '授客'),('hobby', 'unknow');

 

查询显示:

 

 

 

查询需求

纵表转横表:假设attr列的值不重复,且数量有限,要求每行记录的attr值显示为查询结果中的一列(暂且称之为"属性列"),对应行记录的atrr_value值为该属性列的值

 

查询实现

SELECT tb_test.id,

MAX(IF(tb_test.attr = 'age', tb_test.attr_value, NULL)) AS age,

MAX(IF(tb_test.attr = 'sex', tb_test.attr_value, NULL)) AS sex,

MAX(IF(tb_test.attr = 'name', tb_test.attr_value, NULL)) AS `name`,

MAX(IF(tb_test.attr = 'hobby', tb_test.attr_value, NULL)) AS hobby

FROM tb_test;

 

查询结果

 

原文转载:http://www.shaoqun.com/a/477538.html

敦煌网站:https://www.ikjzd.com/w/189

i号店:https://www.ikjzd.com/w/2263

敏思达:https://www.ikjzd.com/w/2304


纵表转横表查询实现By:授客QQ:1033553122欢迎加入全国软件测试交流群:7156436实践环境MySQL5.7创建测试表CREATETABLEtb_test(idINTAUTO_INCREMENTPRIMARYKEY,attrVARCHAR(20),attr_valueVARCHAR(20));插入测试数据INSERTINTOtb_test(attr,attr_value)VALUES(
深兰科技:https://www.ikjzd.com/w/1517
let go:https://www.ikjzd.com/w/825
写给新手卖家,想做好Wish这些点你必须get到:https://www.ikjzd.com/home/108258
亚马逊突发降容该如何应对:https://www.ikjzd.com/home/128634
Amazon Business的收费情况,你了解清楚吗?:https://www.ikjzd.com/home/126253

No comments:

Post a Comment