pivot/unpivot my table

r aper 40 Reputation points
2023-09-20T05:48:57.4833333+00:00

I have a table.

create table TableA(
  ECODE char(2) NULL,
  MEM1 int NULL,
  MEM2 int NULL,
  MEM3 int NULL);

insert into TableA values
('AA',6234,null,2354),
('BB',null,3568,4564),
('CC',1023,3941,null);

Expect output:

ECODE MEM

AA 6234

AA 2354

BB 3568

BB 4564

CC 1023

CC 3941

SQL Server | Other
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-09-20T05:51:16.7133333+00:00

    Hi @r aper

    You can try this.

    select ECODE,MEM from TableA as p
     unpivot (MEM for val in (MEM1,MEM2,MEM3))as t; 
    

    Output:

    User's image

    Best regards,

    Percy Tang

    2 people found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Olaf Helper 47,436 Reputation points
    2023-09-20T06:21:25.1+00:00
    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.