Home > Net >  Microsoft SQL Server PIVOT/UNPIVOT questions
Microsoft SQL Server PIVOT/UNPIVOT questions

Time:11-05

I have the below snippets:

CREATE TABLE [SINGLE_COL]
(
    [COL1] [varchar](50) NULL,
    [COL2] [varchar](50) NULL,
    [COL3] [varchar](50) NULL
)
GO

INSERT INTO [SINGLE_COL]
VALUES ('A', 'B', 'C')
GO
INSERT INTO [SINGLE_COL]
VALUES ('D', 'E', 'F')
GO

select * from [SINGLE_COL]

It returns like this:

COL1 COL2 COL3
A    B    C
D    E    F

I want to turn all the rows into a single column like below:

COL
A
B
C
D
E
F

Here is what I do in oracle:

SELECT col FROM SINGLE_COL
UNPIVOT (col FOR col1 IN (col1, col2, col3));

It's very simple and easy to do in Oracle but not in MS SQL Server!

I believe that I have to use a function UNPIVOT but how??

Thank you!

CodePudding user response:

You can do it in this way:

select Cols from [SINGLE_COL]
unpivot
(
  Cols
  for col in (Col1, Col2, Col3)
) u;
  • Related