在多列上分布任意行

Distribute arbitrary rows on multiple columns

我有 table 个 material。 我需要填写 table.

中的数据输入表格

问题是数据输入表单分为多列,每一列都包含许多 material,如图所示。 如何编写 tsql select 查询以将第一串 material 名称获取到列中,将第二串获取到第二列中,依此类推。

在客户端执行此操作可能最简单,而不是在数据库中执行此操作,但如果您真的想执行此操作,我认为将行分配到 3 组的最简单方法是使用 row_number() 与模 3 并使用它构建单独的列。这将使行的顺序略有不同:

A    B    C
D    E    F
G    H

如果您需要按其他顺序排列它们,则需要将 row_number() 除以行数除以 3。这样您就可以按顺序排列它们

A    D    G
B    E    H
C    F

示例:

select
  max(case when GRP = 0 then VALUE end),
  max(case when GRP = 1 then VALUE end),
  max(case when GRP = 2 then VALUE end)
from
(
    select 
      (row_number() over (order by VALUE)-1) % 3 as GRP, 
      (row_number() over (order by VALUE)-1) / 3 as ROW, 
      VALUE
    from table1
)X
group by ROW

SQL Fiddle

中的示例

编辑:如何以其他方式划分行的示例:

declare @NOLINES int
select @NOLINES = ceiling(count(*) / 3.0) from table1

select
  max(case when GRP = 0 then VALUE end),
  max(case when GRP = 1 then VALUE end),
  max(case when GRP = 2 then VALUE end)
from
(
    select 
      (row_number() over (order by VALUE)-1) / @NOLINES as GRP, 
      (row_number() over (order by VALUE)-1) % @NOLINES as ROW, 
      VALUE
    from table1
)X
group by ROW