纵表结构 TableA
Name|Course|Grade
:--|:--|:--
张三|语文|75
张三|数学|80
张三|英语|90
李四|语文|95
李四|数学|55
横表结构 TableB
Name|语文|数学|英语
:--|:--|:--|:--
张三|75|80|90
李四|95|55|0
先理解:
select Name,
(case Course when '语文' then Grade else 0 end) as 语文,
(case Course when '数学' then Grade else 0 end) as 数学,
(case Course when '英语' then Grade else 0 end) as 英语
from TableA
然后理解标准答案:
select Name,
sum(case Course when '语文' then Grade else 0 end) as 语文,
sum(case Course when '数学' then Grade else 0 end) as 数学,
sum(case Course when '英语' then Grade else 0 end) as 英语
from TableA
group by Name
SELECT 姓名,'语文' AS 科目,语文 AS 成绩 FROM TEST_H2Z UNION ALL
SELECT 姓名,'数学' AS 科目,数学 AS 成绩 FROM TEST_H2Z UNION ALL
SELECT 姓名,'英语' AS 科目,英语 AS 成绩 FROM TEST_H2Z ORDER BY 姓名,科目 DESC;