Problem conversion row to column

declare    @cols    varchar(max),
           @sql     varchar(max)

select    @cols    = stuff((select    ',' + quotename([Class])
                            from    Tb_Student
                            group by [Class]
                            for xml path('')), 1, 1, '')
print    @cols

select    @sql    = 'select * '
        + 'from '
        + '( '
        + '    select Class, Shift, Score from Tb_Student '
        + ') d '
        + 'pivot '
        + '( '
        + '    avg(Score) '
        + '    for [Class] in (' + @cols + ')'
        + ') p '

print    @sql
exec    (@sql)
1 Like