Voici un moyen relativement simple de trier les colonnes. Si vous commencez par unpivot , trier et pivoter vos données, vous obtiendrez des colonnes triées.
Voici Sql Fiddle avec exemple .
-- 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
Vous voudrez peut-être ajouter des lignes d'en-tête afin de savoir quelle valeur provient de quelle colonne. Pour ce faire, j'ajouterais une colonne identifiant l'en-tête/ligne, union all to o
pour obtenir les en-têtes et l'ordre correspondants, ce qui garantirait que ces deux lignes restent ensemble :
(
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