-1

I have a table Table which have some columns and I want to convert column values as columns for another table.

I am attaching one screen shot of my requirement.

The upper table is my main table say Table1 and the below is my required table. enter image description here Thanks

Ash
  • 5,786
  • 5
  • 22
  • 42
Pranay Deep
  • 1,371
  • 4
  • 24
  • 44

2 Answers2

1

Whilst the suggested duplicate will get you part of the way there, you actually need to unpivot then pivot, like this.

(Oh and please don't post images. DDL is appreciated and saves us typing and/or guessing.)

CREATE TABLE #Test( Action char, [Key] INT, Old varchar(5), OldValue  varchar(5), New  varchar(5), NewValue  varchar(5));

INSERT INTO #Test VALUES
('U', 123, 'Col1','Dog','Col1','Dog'),
('U', 123, 'Col2','Cat','Col2','Mouse'),
('U', 123, 'Col3','Honey','Col3','Bee'),
('I', 123, NULL,NULL,'Col45','Sun');


SELECT PVT.Action
      ,PVT.[Key]
      ,PVT.OldCol1
      ,PVT.OldCol2
      ,PVT.OldCol3
      ,PVT.NewCol1
      ,PVT.NewCol2
      ,PVT.NewCol3
      ,PVT.NewCol45 FROM (
SELECT [Action]
      ,[Key]
      ,Label
      ,Value 
FROM #Test
CROSS APPLY (VALUES ('Old'+Old, OldValue), ('New'+New, NewValue)) c(label, value)
)src
PIVOT 
(
MAX(VALUE) FOR Label IN (OldCol1, NewCol1, OldCol2, NewCol2, OldCol3, NewCol3, NewCol45)
)PVT
ORDER BY PVT.Action Desc


Action Key         OldCol1 OldCol2 OldCol3 NewCol1 NewCol2 NewCol3 NewCol45
------ ----------- ------- ------- ------- ------- ------- ------- --------
U      123         Dog     Cat     Honey   Dog     Mouse   Bee     NULL
I      123         NULL    NULL    NULL    NULL    NULL    NULL    Sun

(2 row(s) affected)
Liesel
  • 2,929
  • 2
  • 12
  • 18
0

I guess pivoting will be enough:

SELECT *
FROM (
    SELECT [Action], [Key], 'Old' + Old as [a], OldValue as [Value]
    FROM Table1
    UNION ALL
    SELECT [Action], [Key], 'New' + New, NewValue
    FROM Table1
    ) as p
PIVOT (
    MAX([Value]) FOR [a] IN ([OldCol1],[OldCol2],[OldCol3],[NewCol1],[NewCol2],[NewCol3],[NewCol45])
) as pvt

Output:

Action  Key OldCol1 OldCol2 OldCol3 NewCol1 NewCol2 NewCol3 NewCol45
I       123 NULL    NULL    NULL    NULL    NULL    NULL    Sun
U       123 Dog     Cat     Honey   Dog     Mouse   Bee     NULL

If there are MANY Old and 'New` values then you need dynamic SQL

gofr1
  • 15,741
  • 11
  • 42
  • 52