将ROWS分成多个COLUMN

时间:2019-03-07 19:19:36

标签: sql asp.net sql-server

我有一些有关学生姓名及其名册的信息-
enter image description here

我想将它们分成3组,如下所示。总行数应始终为(3行数/ 3)的上限值
enter image description here

1 个答案:

答案 0 :(得分:3)

您可以通过条件聚合来做到这一点。但是,SQL表表示无序集,因此哪些值最终在任意位置:

select max(case when seqnum % 3 = 0 then name end) as name_1,
       max(case when seqnum % 3 = 0 then roll end) as roll_1,
       max(case when seqnum % 3 = 1 then name end) as name_2,
       max(case when seqnum % 3 = 1 then roll end) as roll_2,
       max(case when seqnum % 3 = 2 then name end) as name_3,
       max(case when seqnum % 3 = 2 then roll end) as roll_3       
from (select t.*, row_number() over (order by (select null)) - 1 as seqnum
      from t
     ) t
group by floor(seqnum / 3);

如果您有订购栏,请使用它代替(select null)