views:

33

answers:

3

I have a table like this

Table1

Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8
1    2    3    4    5    6    7    8
2    2    3    4    5    16   17   18
3    2    3    4    5    26   27   28
4    2    3    4    5    36   37   38

I want the data to be converted in this format

Col1   DerivedCol1  DerivedCol2
1      Col6         6
1      Col7         7
1      Col8         8
2      Col6         16
2      Col7         17
2      Col8         18
3      Col6         26
3      Col7         27
3      Col8         28
4      Col6         36
4      Col7         37
4      Col8         38

Edit: One more important aspect in the question is that i dont know how many columns that i am going to choose to make them as Name, Value pairs and that might change at run time.

+2  A: 
Select Col1, 'Col6', Col6
From Table
Union All
Select Col1, 'Col7', Col7
From Table
Union All
Select Col1, 'Col8', Col8
From Table

There is no dynamic means of doing this other than to build the SQL statement in code.

Thomas
Thanks Thomas !
Baaju
+1  A: 

I would take a look an pivot/unpivot here

Richard Friend
+2  A: 

You could build something like the following in Dynamic SQL

WITH pvt (Col1 , Col2 , Col3 , Col4 , Col5 , Col6 , Col7 , Col8 )
AS
(

SELECT 1,2,3,4,5,6,7,8 UNION ALL
SELECT 2,2,3,4,5,16,17,18 UNION ALL
SELECT 3,2,3,4,5,26,27,28 UNION ALL
SELECT 4,2,3,4,5,36,37,38
)

SELECT Col1, DerivedCol1 ,DerivedCol2
FROM  pvt
UNPIVOT
   (DerivedCol2  FOR DerivedCol1   IN 
      (Col6 , Col7, Col8  )
)AS unpvt;

Returns

Col1        DerivedCol1   DerivedCol2

1           Col6               6
1           Col7               7
1           Col8               8
2           Col6               16
2           Col7               17
2           Col8               18
3           Col6               26
3           Col7               27
3           Col8               28
4           Col6               36
4           Col7               37
4           Col8               38
Martin Smith
Beautiful !!! Can i accept 2 answers ? :)
Baaju
Your answer seems to be the better one ! would have to check for performance between your answer and Thomas's answer. What is your general opinion about the performance comparisons between using a PIVOT and the one that Thomas just answered.
Baaju
@Baaju - I'd guess that they will probably be similar on that front. Would be interested if you discover any differently.
Martin Smith