Search code examples
sql-servert-sqldata-entry

Distribute arbitrary rows on multiple columns


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

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. enter image description here 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.


Solution

  • 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
    

    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
    

    Example:

    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
    

    Example in SQL Fiddle

    Edit: 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