Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is relatively simple way to sort columns. If you first <a href="http://msdn.microsoft.com/en-us/library/ms177410%28v=sql.90%29.aspx" rel="nofollow">unpivot</a>, sort and <a href="http://msdn.microsoft.com/en-us/library/ms177410%28v=sql.90%29.aspx" rel="nofollow">pivot</a> your data, you will get sorted columns.</p> <p><a href="http://sqlfiddle.com/#!3/6d442/12" rel="nofollow">Here is Sql Fiddle with example</a>.</p> <pre><code>-- 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 </code></pre> <p>You might want to add header rows so you would know which value come from which column. To do this I would add a column identifying header/row, union all to <code>o</code> to get corresponding headers and order by which would ensure that these two rows stay together:</p> <pre><code> ( 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 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload