2016-07-01 221 views
1

我有一个表如下格式 enter image description here 我需要将其转换为这种格式SQL:转换成多列行

enter image description here

所以基本上我期待多列转换为行。有人可以帮我弄这个吗?

感谢

+1

请使用纯文本格式的样本数据,而不是图像。 –

+0

查看'UNPIVOT' –

回答

3

尝试

select * 
    from yourTable 
    unpivot (
    Value 
    for NewCol in (Value1, Value2, Value3,Value4, Value5) 
) up 
+0

感谢nazark,这对我有用。欣赏这里的帮助。 –

0

转换列行被称为unpivoting。将行转换为列是旋转的。

一种解决数据不透明的方法是将apply operatortable value constructor合并。

本示例使用common table expression (CTE)返回3个样本记录。

Id ColumnOne ColumnTwo ColumnThree 
1 a   b   c 
2 d   e   f 
3 g   h   i 

-- Unpivoting with apply and VALUES.   
WITH SampleData AS 
    (
     /* This CTE returns 3 sample records. 
     */    
     SELECT 
      cte.* 
     FROM 
      (
       VALUES 
        (1, 'a', 'b', 'c'), 
        (2, 'd', 'e', 'f'), 
        (3, 'g', 'h', 'i') 
      ) AS cte(Id, ColumnOne, ColumnTwo, ColumnThree) 
    ) 
SELECT 
    sd.Id, 
    ca.* 
FROM 
    SampleData AS sd 
     CROSS APPLY 
      (
       VALUES 
        (ColumnOne), 
        (ColumnTwo), 
        (ColumnThree) 
      ) AS ca (ColumnFour) 
; 

返回的输出如下所示:

Id ColumnFour 
1 a 
1 b 
1 c 
2 d 
2 e 
2 f 
3 g 
3 h 
3 i 

个人而言,我更喜欢@ nazark的做法。使用UNPIVOT运算符可帮助其他人遵循代码的意图。如果这个答案帮助你请accept it。接受答案奖励贡献者的努力,并帮助具有相同问题的其他人找到工作答案。

+0

感谢您解释所有这些.. nazark的回复帮助我获得了所需的结果 –