Search code examples
selectsql-server-2008-r2unpivot

Dynamic SQL SELECT column names and related data using UNPIVOT


I have a table called PERSONNELSERVICELEVELS with general info such as ID and Name, but also many columns identified as ServiceLevel% as follows:

Person_ID  Last_Name  First_Name  ServiceLevel1  ServiceLevel2  ServiceLevel3  etc.
---------  ---------  ----------  -------------  -------------  -------------
222        Doe        John        4              5              NULL  
555        Doe        Jane        2              6              9

I would like to create a SELECT statement to produce this output:

Person_ID  Last_Name  First_Name  ServiceLevel  Level
---------  ---------  ----------  ------------  ----- 
222        Doe        John        ServiceLevel1 4
222        Doe        John        ServiceLevel2 5
222        Doe        John        ServiceLevel3 NULL
555        Doe        Jane        ServiceLevel1 2
555        Doe        Jane        ServiceLevel2 6
555        Doe        Jane        ServiceLevel3 9

Thanks.


Solution

  • To turn columns into rows, so to speak, you might use a UNION, as in:

    select Person_ID, Last_Name, First_Name, 'ServiceLevel1' as ServiceLevel, ServiceLevel1 as [Level]
    from PERSONNELSERVICELEVELS
    union all
    select Person_ID, Last_Name, First_Name, 'ServiceLevel2' as ServiceLevel, ServiceLevel2 as [Level]
    from PERSONNELSERVICELEVELS
    union all
    -- etc.
    

    I'm using union all here because union implicitly runs a distinct operation as well, and that is unnecessary here.

    You can also do this type of thing with UNPIVOT.