SQL Server语言 - 将行旋转为固定数量的列,其中列排序而不是行



我正在使用SQL Server 2012,我正在尝试"透视"表输出,以便我可以重新格式化结果表以显示给用户。 描述它的最简单方法是用一个例子:

输入

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

输出

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

我想过使用临时表来存储相关的行值,然后查询这些值,但这似乎有点冗长。必须有一种超越我专业知识的巧妙方法来实现这一点。

使用窗口函数枚举和计数行,然后使用一些算术来分配位置:

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)

最新更新