sql >> Base de Datos >  >> RDS >> Sqlserver

ordenar los resultados por columna, no por fila

Aquí hay una forma relativamente simple de ordenar las columnas. Si primero unpivot , ordenar y girar sus datos, obtendrá columnas ordenadas.

Aquí está Sql Fiddle con ejemplo .

-- 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

Es posible que desee agregar filas de encabezado para saber qué valor proviene de qué columna. Para hacer esto, agregaría una columna que identifique el encabezado/fila, unirá todo a o para obtener los encabezados correspondientes y el orden en que garantizaría que estas dos filas permanezcan 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