如何将列值转换为teradata中的列名?

时间:2014-03-07 15:20:47

标签: sql teradata

我有一张表格如下:

Name     Subjects 
X         math 
Y         science
Z         english

我需要以下格式的报告:

  Name      math     science     english
    X         Y         N          N
    Y         N         Y          N
    Z         N         N          Y

如何使用单个选择查询实现此目的?

1 个答案:

答案 0 :(得分:3)

这是一个常见的问题,搜索“PIVOT查询”: - )

假设一个名称可以有多个主题,则需要使用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