Pivot/UnPivot 2 columns

Punnet Patel 21 Reputation points
2023-08-29T17:13:58.82+00:00

create table #t (marks int, studentname varchar (50), subject varchar (50))

insert into #t values (70, 'A1', 'React')

insert into #t values (75, 'A1', 'Angular')

insert into #t values (80, 'A1', 'Vue')

insert into #t values (60, 'A2', 'React')

insert into #t values (65, 'A2', 'Angular')

insert into #t values (68, 'A2', 'Vue')

insert into #t_values (77, 'A3', 'React')

insert into #t values (88, 'A3', 'Vue')

insert into #t values (82, 'A4', 'Angular')

insert into #t values (85, 'A4', 'Vue')

SELECT * from #t

I have the table with the above structure and as per image1. Can I pivot/unpivot last 2 columns like image2

image2.PNG

image1.PNG

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,672 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Jingyang Li 5,891 Reputation points
    2023-08-29T19:52:33.3933333+00:00

    SELECT studentname [class], MAX(Case when subject='React' then marks Else null end) [React]

    , MAX(Case when subject='Angular' then marks Else null end) [Angular]

    , MAX(Case when subject='Vue' then marks Else null end) [Vue]

    from #t

    group by studentname

    0 comments No comments

  2. PercyTang-MSFT 12,501 Reputation points Microsoft Vendor
    2023-08-30T02:14:53.95+00:00

    Hi @Punnet Patel

    You can try this.

    ;with CTE as(
      select * from #t as c
      pivot(max(marks) for subject in ([React],[Angular],[Vue])) as t)
    select studentname as Class,React,Angular,Vue from CTE;
    

    Output:

    User's image

    Best regards,

    Percy Tang

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.