简体   繁体   中英

Transpose rows to columns - pivot in SQL Server 2008 using an id column

I have a table with columns logid , skilllevel , logskill and a sample of data looks like this:

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

I want to get it arranged like the following:

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

skilllevel1 corresponds to logonskill1 as so on skillposition is the substring of logonskill

How can I achieve this?

You can use this query.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM