简体   繁体   中英

SQL Server - Pivoting rows into fixed number of columns with columns sorted rather than rows

I am using SQL server 2012 and I am trying to 'pivot' a table output so that I can reformat a results table for display to the user. The easiest way to describe it is with an example:

Input

MyCol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Output

Col1    Col2    Col3
1       7       13
2       8       14
3       9       15
4       10      16
5       11      17
6       12

I thought about using temporary tables to store the relevant row values and then query those but it seems a little long winded. There has to be a slick way to achieve this beyond my expertise.

Use window functions to enumerate and count the rows and then some arithmetic to assign the position:

select (case when mycol < ceil(cnt / 3) then mycol end) as col1,
       (case when mycol >= ceil(cnt / 3) and mycol < 2*ceil(cnt / 3) then mycol end) as col2,
       (case when mycol >= 2*ceil(cnt / 3) then mycol end) as col3       
from (select t.*,
             row_number() over (order by mycol) - 1 as seqnum,
             count(*) over () as cnt
      from t
     ) t
group by mycol % ceil(cnt / 3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM