将表转换为键值对

问题描述 投票:0回答:2

我想把我现在的桌子弄平。目前我能够通过迭代方法实现这一点,但运行时间很差。我查询了表,然后使用游标迭代并插入到新表中。

我当前的表格有很多列,我正试图将其展平。可能是逆向的。

RecordId    FirstName    LastName    Country     Grade
-------------------------------------------------------
1           Joe          Fresh       Canada      95
2           John         Smith       Canada      94

新桌子看起来像这样

RecordId    Key        Value
--------------------------------
1           FirstName   Joe
1           LastName    Fresh
1           Country     Canada
1           Grade       95
2           FirstName   John
2           LastName    Smith
2           Country     Canada
2           Grade       94

我可以得到一些指导吗

我尝试了 unpivot 并能够压平桌子,但我错过了

RecordId
专栏

select [Key], [Value]
from
(
  SELECT * 
  FROM test
) src
unpivot
(
  [Value] for [Key] in ([RecordId],[FirstName],[LastName], [Country], [Grade])
)
sql-server ssms
2个回答
2
投票

是的,它是不可旋转的。请通过将 RecordId 列添加到 UNPIVOT 操作之前的 SELECT 语句,将其包含在反透视结果中。试试这个:

SELECT RecordId, [Key], [Value]
FROM
(
  SELECT RecordId, FirstName, LastName, Country, Grade
  FROM test
) src
UNPIVOT
(
  [Value] FOR [Key] IN (FirstName, LastName, Country, Grade)
) unpvt;

1
投票

我发现使用cross apply通常更容易并且允许更多的灵活性:

select t.RecordId, v.*
from t
cross apply(values
    ('FirstName', FirstName), 
    ('LastName', LastName), 
    ('Country', Country), 
    ('Grade', Cast(Grade as varchar(10)))
)v([key], [value]);
© www.soinside.com 2019 - 2024. All rights reserved.