将列值转换为多个记录

时间:2010-11-16 17:18:51

标签: sql-server tsql sql-server-2008 pivot

在SQL Server 2008中,我有一个包含以下列和数据的表

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

我想创建新表或更改上表,数据显示为

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

由于

3 个答案:

答案 0 :(得分:3)

或使用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 != ''

答案 1 :(得分:1)

不完全是我最优雅的答案,但我认为它仍然有用

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

答案 2 :(得分:1)

您可能对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;