Sagar Dev Timilsina
Sagar Dev Timilsina

Reputation: 1400

Pivot in sql for multiple columns

I have a table as following:

enter image description here

Using pivot I need the following output:

enter image description here

The query should not use Union set operator.

Upvotes: 1

Views: 228

Answers (1)

gotqn
gotqn

Reputation: 43666

You could first do UNPIVOT to turn data in the following format:

enter image description here

and then do PIVOT by the Type column:

enter image description here

This is full working example:

DECLARE @DataSource TABLE
(
    [CatDes] CHAR(1)
   ,[val1] TINYINT
   ,[val2] TINYINT
);

INSERT INTO @DataSource ([CatDes], [val1], [val2])
VALUES ('a', 1 ,2)
      ,('b', 3 ,4)
      ,('c', 5 ,6)
      ,('d', 7 ,8);

SELECT *
FROM @DataSource
UNPIVOT
(
    [Value] FOR [Type] IN ([val1], [val2])
) UNPVT
PIVOT
(
    MAX([Value]) FOR [CatDes] IN ([a], [b], [c], [d])
) PVT

Of course, when you are using PIVOT and UNPIVOT you should hard-coded the column values. I guess, in your real case, this is not an option, so I will recommend to you to use a dynamic T-SQL statement - build the statement as a string and then execute it using sp_executesql.

Upvotes: 4

Related Questions