在 UNPIVOT 期间添加列名称的列

Add Columns of Columns name during UNPIVOT

我的 Unpivot 正在运行,但我缺少一个列来放置 Unpivot 列的名称。到目前为止,所有数据都很好,我想在它旁边添加 'original' 列名称。

我的查询('ColumnName'是为了说明我的问题,但什么也没做):

SELECT 'ColumnName', myData, wename, weblangue, wid FROM website
UNPIVOT
(
myData FOR names IN (sport, yahoo, mobile, di, onet, player)
) temp

我想在每个结果行中添加相应的名称:(sport、yahoo、mobile、di、onet、player) 我知道我可以使用此查询检索列名称:

SELECT C.name FROM sys.columns c WHERE c.object_id = OBJECT_ID('dbo.website')

与其尝试检索列名称,因为它每 6 行重复一次,我只需要为每 n 行手动添加名称即可:

SELECT
CASE 
    WHEN ROW_NUMBER() over (ORDER BY w_id)%6 =1 THEN 'sport'
    WHEN ROW_NUMBER() over (ORDER BY w_id)%6 =2 THEN 'yahoo'
    WHEN ROW_NUMBER() over (ORDER BY w_id)%6 =3 THEN 'mobile'
    WHEN ROW_NUMBER() over (ORDER BY w_id)%6 =4 THEN 'di'
    WHEN ROW_NUMBER() over (ORDER BY w_id)%6 =5 THEN 'onet'
    WHEN ROW_NUMBER() over (ORDER BY w_id)%6 =0 THEN 'player'
END AS Label, 
isPlayed, wename, webgue, w_id from
 website
UNPIVOT
(
 isPlayed for names in (sport, yahoo, mobile, di, onet, player)
) temp

您缺少名为 names 的新列(您将其包含在您的 unpivot 语句中),该列包含已旋转的列名称!

SELECT names, myData, wename, weblangue, wid FROM website
UNPIVOT
(
myData FOR names IN -- You are declaring the pivoting columns names as "names" here!!!
    (sport, yahoo, mobile, di, onet, player)
) temp