Aqui está uma maneira relativamente simples de classificar colunas. Se você primeiro unpivot , classifique e pivot seus dados, você obterá colunas classificadas.
Aqui está Sql Fiddle com exemplo .
-- Assign arbitrary numbers to records
-- You might skip this part if you have unique column
-- in which case you should replace RecordNumber with this ID
; with numbered as
(
select *,
row_number() over (order by (select null)) RecordNumber
from test
),
-- Generate order by
-- For all the columns in record.
-- Rn will always be in range
-- 1..NumberOfColumns
-- Order is done on unpivoted data
ordered as
(
select *,
row_number() over (partition by RecordNumber
order by v desc) rn
from numbered
-- list all the columns here
-- v is for value
-- c is for column
unpivot (v for c in (c1, c2, c3)) u
)
-- Finally return the data in original layout
select RecordNumber,
[1] c1,
[2] c2,
[3] c3
from
(
-- Only the columns needed by the query
-- Pivot will not play nice even if you
-- Select only subset of columns in
-- outer query
select RecordNumber,
v,
Rn
from ordered
) o
-- Get value for row numbers 1..NumberOfColumns
pivot (min(v) for Rn in ([1], [2], [3])) p
Você pode querer adicionar linhas de cabeçalho para saber qual valor vem de qual coluna. Para fazer isso, eu adicionaria uma coluna identificando o cabeçalho/linha, unindo tudo em
o
para obter os cabeçalhos e a ordem correspondentes para garantir que essas duas linhas permaneçam juntas: (
select RecordNumber,
v,
Rn,
1 HdrRow
from ordered
union all
select RecordNumber,
c, -- Column name is in c
Rn,
0 HdrRow
from ordered
) o
...
order by RecordNumber, HdrRow