当前位置:网站首页>MySQL row column conversion (updated version)

MySQL row column conversion (updated version)

2022-06-13 07:22:00 Dongbei bird

Recommended if The sentence of :
if( Want to become the column name of the row = ‘ The value of the column ’, Another column name ) ‘ Alias this field ’

Create table statement

create table test (Date varchar(10), item char(10),saleqty int);
insert test values('2010-01-01','AAA',8);
insert test values('2010-01-02','AAA',4);
insert test values('2010-01-03','AAA',5);
insert test values('2010-01-01','BBB',1);
insert test values('2010-01-02','CCC',2);
insert test values('2010-01-03','DDD',6);

 Insert picture description here

SELECT * ,
case item when 'AAA' THEN saleqty ELSE 0 end as A,
case item when 'BBB' THEN saleqty ELSE 0 end as B,
case item when 'CCC' THEN saleqty ELSE 0 end as C
FROM TEST 

 Insert picture description here

select *,
if(item = 'AAA',saleqty,0) 'A',
if(item = 'BBB',saleqty,0) 'B',
if(item = 'CCC',saleqty,0) 'C'
FROM TEST

 Insert picture description here

select *,
max(if(item = 'AAA',saleqty,0)) 'A',
max(if(item = 'BBB',saleqty,0) )'B',
max(if(item = 'CCC',saleqty,0) )'C'
FROM TEST

 Insert picture description here

原网站

版权声明
本文为[Dongbei bird]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270549280144.html