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

Insert Data from old SQL table, to new one with columns changed to rows

我目前有一个 table 看起来与此类似:

Old Table(example only)

我需要将数据导入到新的 table,但要将列 headers 变成行并为每一行赋值。类似这样。

New Table(example only)

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

你应该选择 unpivot,试试下面的查询。一般来说,Pivot 会减少总行数,而 Unpivot 会增加总行数。

select SN,Property,Value

from tbl

unpivot

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

如果您没有很多列,您可以随时尝试类似的方法:

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>