SQL: Dynamic view with column names based on column values in source table

前端 未结 1 1222
庸人自扰
庸人自扰 2020-12-10 08:09

Given the two sample tables here:

Tickets Table

ID  User    Description

0   James   This is a support ticket
1   Fred    This is a          


        
相关标签:
1条回答
  • 2020-12-10 08:53

    You can perform this with a PIVOT. When doing the PIVOT you can do it one of two ways, with a Static Pivot that you will code the rows to transform or a Dynamic Pivot which will create the list of columns at run-time:

    Static Pivot (See SQL Fiddle for Demo):

    select id, [user], [engineer], [manu], [OS]
    from 
    (
        select t.id
            , t.[user]
            , p.ticketid
            , p.label
            , p.value
        from tickets t
        inner join properties p
            on t.id = p.ticketid
    ) x
    pivot
    (
        min(value)
        for label in ([engineer], [manu], [OS])
    ) p
    

    Or you can use a Dynamic Pivot (See SQL Fiddle for Demo):

    DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);
    
    select @cols = STUFF((SELECT distinct ',' + QUOTENAME(p.label) 
                        from tickets t
                        inner join properties p
                            on t.id = p.ticketid
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')
    
    set @query = 'SELECT id, [user], ' + @cols + ' from 
                 (
                     select t.id
                            , t.[user]
                            , p.ticketid
                            , p.label
                            , p.value
                        from tickets t
                        inner join properties p
                            on t.id = p.ticketid
                ) x
                pivot 
                (
                    min(value)
                    for label in (' + @cols + ')
                ) p '
    
    execute(@query)
    

    Both query will return the same results.

    0 讨论(0)
提交回复
热议问题