user3392889
user3392889

Reputation: 23

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?

Upvotes: 2

Views: 1241

Answers (1)

dnoeth
dnoeth

Reputation: 60462

That'a common question, search for "PIVOT query" :-)

Assuming one Name can have multiple Subjects you need to use MAX/GROUP BY, otherwise simply remove the aggregation.

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

Upvotes: 3

Related Questions