SQL行转列、列转行
解题思路
【总结】
行列转换就是如下图所示两种展示形式的互相转换:
(上表/行表:student1;下表/列表:student2)
【行转列——MAX/SUM+CASE WHEN+GROUP BY】
SELECT name,
MAX(CASE WHEN subject='语文' THEN score ELSE 0 END) AS "语文",
MAX(CASE WHEN subject='数学' THEN score ELSE 0 END) AS "数学",
MAX(CASE WHEN subject='英语' THEN score ELSE 0 END) AS "英语"
FROM student1
GROUP BY name
【列转行——MAX+UNION+GROUP BY】
SELECT NAME,'语文' AS subject,MAX("语文") AS score
FROM student2 GROUP BY NAME
UNION
SELECT NAME,'数学' AS subject,MAX("数学") AS score
FROM student2 GROUP BY NAME
UNION
SELECT NAME,'英语' AS subject,MAX("英语") AS score
FROM student2 GROUP BY NAME
代码
-- Write your MySQL query statement below
select product_id,'store1' store,store1 price
from Products where store1 is not null
group by 1
union all
select product_id,'store2' store,store2 price
from Products where store2 is not null
group by 1
union all
select product_id,'store3' store,store3 price
from Products where store3 is not null
group by 1