Mysql-sql行轉列
原始資料如下圖所示:(商品的銷售明細)
date=業務日期;Item=商品名稱;saleqty=銷售數量
-- 建立測試資料(表)
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);
實現的方法和思路如下:兩個方法
-- 實現結果的靜態SQL語句寫法
-- 整理報表需要的格式
方法一:case item when x then xx when y then yy end
select date,
case item when 'AAA' then saleqty end as AAA,
case item when 'BBB' then saleqty end as BBB,
case item when 'CCC' then saleqty end as CCC,
case item when 'DDD' then saleqty end as DDD
from test;
方法二:if(條件判斷,成立結果,不成立結果)
select date,
if (item = 'AAA',saleqty,null) as AAA,
if (item = 'BBB',saleqty,null) as BBB,
if (item = 'CCC',saleqty,null) as CCC,
if (item = 'DDD',saleqty,null) as DDD
from test;
-- 按日期彙總行
select date,
sum(case item when 'AAA' then saleqty end)as AAA,
sum(case item when 'BBB' then saleqty end)as BBB,
sum(case item when 'CCC' then saleqty end)as CCC,
sum(case item when 'DDD' then saleqty end)as DDD
from test group by date;
select date,
sum(if (item = 'AAA',saleqty,null)) as AAA,
sum(if (item = 'BBB',saleqty,null)) as BBB,
sum(if (item = 'CCC',saleqty,null)) as CCC,
sum(if (item = 'DDD',saleqty,null)) as DDD
from test group by date;
-- 處理資料:將空值的欄位填入數字0;
select date,
ifnull(sum(case item when 'AAA' then saleqty end) ,0)as AAA,
ifnull(sum(case item when 'BBB' then saleqty end) ,0)as BBB,
ifnull(sum(case item when 'CCC' then saleqty end) ,0)as CCC,
ifnull(sum(case item when 'DDD' then saleqty end) ,0)as DDD
from test group by date;
select date,
ifnull(sum(if (item = 'AAA',saleqty,null)),0) as AAA,
ifnull(sum(if (item = 'BBB',saleqty,null)),0) as BBB,
ifnull(sum(if (item = 'CCC',saleqty,null)),0) as CCC,
ifnull(sum(if (item = 'DDD',saleqty,null)),0) as DDD
from test group by date;
靜態SQL語句編寫完成!
其實有一步驟有點多餘:可以直接if(,,0),而不是if(,,null)
select date,
if (item = 'AAA',saleqty,0) as AAA,
if (item = 'BBB',saleqty,0) as BBB,
if (item = 'CCC',saleqty,0) as CCC,
if (item = 'DDD',saleqty,0) as DDD
from test;
select date,
sum(if (item = 'AAA',saleqty,0)) as AAA,
sum(if (item = 'BBB',saleqty,0)) as BBB,
sum(if (item = 'CCC',saleqty,0)) as CCC,
sum(if (item = 'DDD',saleqty,0)) as DDD
from test group by date;
靜態SQL語句編寫完成!
參考網址https://www.cnblogs.com/ShaYeBlog/p/3594517.html