Unpivot with column name

前端 未结 4 2163
忘掉有多难
忘掉有多难 2020-11-22 06:10

I have a table StudentMarks with columns Name, Maths, Science, English. Data is like

Name,  Maths, Science, English  
Tilak, 90         


        
4条回答
  •  无人共我
    2020-11-22 07:03

    You may also try standard sql un-pivoting method by using a sequence of logic with the following code.. The following code has 3 steps:

    1. create multiple copies for each row using cross join (also creating subject column in this case)
    2. create column "marks" and fill in relevant values using case expression ( ex: if subject is science then pick value from science column)
    3. remove any null combinations ( if exists, table expression can be fully avoided if there are strictly no null values in base table)

       select *
       from 
       (
          select name, subject,
          case subject
          when 'Maths' then maths
          when 'Science' then science
          when 'English' then english
          end as Marks
      from studentmarks
      Cross Join (values('Maths'),('Science'),('English')) AS Subjct(Subject)
      )as D
      where marks is not null;
      

提交回复
热议问题