The number of levels is not fixed:
Declare @select varchar(max) = 'SELECT ',
@from varchar(max) = 'FROM ',
@where varchar(max) = 'WHERE ',
@query varchar(max)= '';
SELECT @select = @select + 't' + cast([level] as varchar(max)) + '.[value]+''-''+',
@from = @from + 'yourTable t' + cast([level] as varchar(max)) + ',',
@where = @where + 't' + cast([level] as varchar(max)) + '.[level] = ' + cast([level] as varchar(max)) + ' AND '
FROM yourTable
GROUP BY [level]
Set @query = SUBSTRING(@select, 1, len(@select) - 5) + ' ' +
SUBSTRING(@from, 1, len(@from) - 1) + ' ' +
SUBSTRING(@where, 1, len(@where) - 4) + ' ORDER BY 1'
EXEC(@query)
source
share