简体   繁体   English

如何在Teradata中将列值转换为列名?

[英]How to convert column values to column names in teradata?

I have a table as follows: 我有一张桌子,如下所示:

Name     Subjects 
X         math 
Y         science
Z         english

I need a report in the following format: 我需要以下格式的报告:

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

How do I achieve this using a single select query? 如何使用单个选择查询实现此目的?

That'a common question, search for "PIVOT query" :-) 这是一个常见问题,请搜索“ PIVOT查询” :-)

Assuming one Name can have multiple Subjects you need to use MAX/GROUP BY, otherwise simply remove the aggregation. 假设一个名称可以有多个主题,则需要使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM