SQL Server-将行数据透视到固定数量的列中,并对列而不是行进行排序
我正在使用SQL server 2012,我正在尝试“透视”表输出,以便可以重新格式化结果表以显示给用户。 最简单的描述方法是用一个例子: 输入 输出SQL Server-将行数据透视到固定数量的列中,并对列而不是行进行排序,sql,sql-server,Sql,Sql Server,我正在使用SQL server 2012,我正在尝试“透视”表输出,以便可以重新格式化结果表以显示给用户。 最简单的描述方法是用一个例子: 输入 输出 Col1 Col2 Col3 1 7 13 2 8 14 3 9 15 4 10 16 5 11 17 6 12 我曾考虑使用临时表存储相关的行值,然后查询这些值,但这似乎有点冗长。必须有一种巧妙的方法来实
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)
你怎么转动桌子?pivot背后的逻辑是什么?请澄清。1和2发生了什么?…1和2出现了一个拼写错误我使用“pivot”一词是因为我很难用其他方式来描述它。这就是分页和格式化的报告工作,当然你可以用动态SQL实现查询输出,但这是浪费时间。
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)