将旧SQL表中的数据插入到新表中,并将列更改为行

时间:2017-11-16 20:45:31

标签: sql sql-server unpivot

我目前有一个类似于此的表:

Old Table(example only)

我需要将数据导入到新表中,但是将列标题分为行和每个值的值。与此类似。

New Table(example only)

我会使用Pivot还是Unpivot来执行此操作?我有很多列需​​要以这种方式转换大约700行。

2 个答案:

答案 0 :(得分:3)

您应该使用unpivot,请尝试以下查询。一般来说,Pivot会减少总行数,而Unpivot会增加行数。

select SN,Property,Value

from tbl

unpivot

(Value for Property in (Property1,Property2,Property3,Property4) ) as tblunpvt

答案 1 :(得分:1)

如果您没有很多专栏,您可以尝试以下方式:

SELECT SN, 'Property1' as Property, Property1 as Value from <TABLE>
UNION ALL
SELECT SN, 'Property2' as Property, Property2 as Value from <TABLE>
UNION ALL
SELECT SN, 'Property3' as Property, Property3 as Value from <TABLE>