[英]SQL Server - Pivoting rows into fixed number of columns with columns sorted rather than rows
我正在使用 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.