我有一个表格如下:
Name Subjects
X math
Y science
Z english
我需要以下格式的报告:
Name math science english
X Y N N
Y N Y N
Z N N Y
如何使用单个选择查询来实现此目的?
最佳答案
这是一个常见问题,搜索“PIVOT 查询”:-)
假设一个Name可以有多个Subject,您需要使用MAX/GROUP BY,否则只需删除聚合即可。
select
Name,
max(case when Subjects = 'math' then 'Y' else 'N' end) as Math,
max(case when Subjects = 'science' then 'Y' else 'N' end) as Science,
max(case when Subjects = 'english' then 'Y' else 'N' end) as English
from tab
group by Name
关于sql - 如何将 Teradata 中的列值转换为列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22253965/