将行转置为列 - 使用id列在SQL Server 2008中进行透视

时间:2018-01-12 20:45:21

标签: sql sql-server pivot

我有一个包含logidskilllevellogskill列的表格,数据样本如下所示:

logid  skilllevel  logonskill  skillposition
--------------------------------------------
101    90          1           1
101    40          2           2
102    30          4           1

我想按照以下方式安排:

logid  skilllevel1  skilllevel2 skilllevel3 logonskill1 logonskill2 logonskill3 
101    90           40          60          1           2           3
102    30           20          10          4           5           6

skilllevel1对应logonskill1,因此skillpositionlogonskill

的子字符串

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以使用此查询。

SELECT * FROM (
    select logid, skilllevel val, 'skilllevel' + CONVERT(VARCHAR,skillposition) colName  from MyTable
    UNION ALL 
    select logid, logonskill val, 'logonskill' + CONVERT(VARCHAR,skillposition) colName  from MyTable
) SRC
PIVOT (MAX(val) FOR colName IN ([skilllevel1],[skilllevel2],[skilllevel3],[logonskill1],[logonskill2],[logonskill3])) AS PVT