Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top