1

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.

gotqn
  • 42,737
  • 46
  • 157
  • 243
Sagar Dev Timilsina
  • 1,310
  • 15
  • 32
  • Possible duplicate: http://stackoverflow.com/questions/20111418/sql-server-transpose-rows-to-columns You're looking for Transpose from Rows -> Columns. – Evaldas Buinauskas Apr 15 '15 at 09:31
  • I have done it using pivot for individual val1 and val2 and union the results for the final output.. I checked the above link "Evaldas Buinauskas" , but I need my column name in rows.. ie. val1 and val2 in rows. – Sagar Dev Timilsina Apr 15 '15 at 09:35

1 Answers1

4

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.

gotqn
  • 42,737
  • 46
  • 157
  • 243