在多列上分布任意行

时间:2023-04-03
本文介绍了在多列上分布任意行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张材料表.我需要填写该表中的数据输入表.

I have a table of materials. I need to fill a data entry form from that table.

问题是数据输入表单被分成多列,每列包含许多材料,如图所示.如何编写 tsql select 查询,将第一组材料名称放入一列,将第二组材料名称放入第二列,依此类推.

The problem is that the data entry form is divided into multiple columns each one containing a a number of materials as in the picture. How to write a tsql select query to obtain the first bunch of material names into a column, the second bunch into a second column and so on.

推荐答案

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

It might be easiest to do this in the client side, and not in the database, but if you really want to do this, I would assume the simplest way to distribute rows into 3 groups is to use row_number() with modulo 3 and build separate columns using that. That will order the rows slightly differently:

A    B    C
D    E    F
G    H

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

If you need to have them in the other order, then you need to divide the row_number() with the number of rows divided by 3. That will you get them in the order

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

示例如何以另一种方式划分行:

Example how to divide the rows the other way:

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

这篇关于在多列上分布任意行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:仅更新具有共享/相似值的行 下一篇:在子集中具有特定值的父级的 SQL 查询

相关文章

最新文章