2

In SQL Server 2008, I have a table with following columns and data

Date    Name    Colors  Color1  Color2  Color3
Nov01   John    Red
Nov02   Mike    Green   Blue    Grey
Nov03   Melissa Yellow  Orange
Nov10   Rita    Pink    Red

I want to make new table or change above table with data shown as

Date    Name    Colors
Nov01   John    Red
Nov02   Mike    Green
Nov02   Mike    Blue
Nov02   Mike    Grey
Nov03   Melissa Yellow
Nov03   Melissa Orange
Nov10   Rita    Pink
Nov10   Rita    Red

Thanks

skaffman
  • 398,947
  • 96
  • 818
  • 769
user219628
  • 3,755
  • 8
  • 35
  • 37

3 Answers3

3

Or using PIVOT & UNPIVOT

SELECT  t.Date,
        unpvt.Name,
        unpvt.Color
FROM 
   (SELECT  Name, Colors, Color1, Color2, Color3
   FROM dbo.MYTABLE) p
UNPIVOT
   (Color FOR [Date] IN 
      (Colors, Color1, Color2, Color3)
)AS unpvt
Join dbo.MYTABLE t on t.[Name] = unpvt.[Name]
Where unpvt.Color != ''
codingbadger
  • 42,678
  • 13
  • 95
  • 110
  • Hello, I have similar question for opposite situation. I would appreciate if you can respond http://stackoverflow.com/questions/4256441/convert-multiple-records-into-once-column – user219628 Nov 23 '10 at 13:26
1

Not exactly my most elegant answer but i think it will still work

Select Date, Name, Colors as Colors
Where Colors is not null
Union All
Select Date, Name, Color1 as Colors
Where Color1 is not null
Union All
Select Date, Name, Color2 as Colors
Where Color2 is not null
Union All
Select Date, Name, Color3 as Colors
Where Color3 is not null
Jagmag
  • 10,283
  • 1
  • 34
  • 58
1

You may be interested in UNPIVOT

SELECT [Date], [Name], [Colors]
FROM 
   (SELECT [Date], [Name], [Color1], [Color2], [Color3]
   FROM myColors) p
UNPIVOT
   ([Colors] FOR x IN 
      ([Color1], [Color2], [Color3])
) AS unpvt;
bobs
  • 21,844
  • 12
  • 67
  • 78