1

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.

Ehab
  • 566
  • 6
  • 24

1 Answers1

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

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
James Z
  • 12,209
  • 10
  • 24
  • 44
  • Thank you very much. Would you give another example to show the rows in the other way as in the question? – Ehab Jan 25 '16 at 06:19
  • You just need to have the number of rows + swap modulo and division the other way. Added example for that. – James Z Jan 25 '16 at 07:52